Read File as String in Python

File To String

In this article, we will try to understand how to read a text file as a string in different formats using different built-in functions and methods in Python.


Using read() method

We can read the data stored in a text file using the read() method. This method converts the data present in the text file into a string format. But first, we need to use the open() function to open the file. Always remember to add replace() function along with read() function to replace the new line characters with specified characters so that the data returned looks even and more readable.

#without replace()

with open("AskPython.txt") as f:
    data = f.read()
    
print(data)

Output:

AskPython Website is very useful

Python Programming language

How to read files as strings in python?
#using replace() everything is returned in one line.

with open("AskPython.txt") as file:
    data = file.read().replace('\n',' ')
    
print(data)

Output:

AskPython Website is very useful. Python Programming language. How to read files as strings in python?

Using pathlib module

pathlib is a python module available in Python 3.2 or later. It makes overall working with files and filesystems much more efficient. e do not need to use os and os.path functions, with pathlib everything can be done easily through operators, attribute accesses, and method calls. We use the read.text() function to read the data from the file in a string format. We can also add the replace() method if needed along with read.text() just like explained in the previous example.

from pathlib import Path

data = Path("AskPython.txt").read_text()
print(data)

Output:

AskPython Website is very useful
Python Programming language
How to read files as strings in python?

Conclusion

While working and developing different projects, many times files are to be included in the programming. To make working with files easier, we can read the data present in the file by extracting them into a string format. This article discusses different methods to read a file as a string in Python.

Also, understand how to solve Python filenotfounderror error by clicking here.