In this Python tutorial, you will learn how to read a file as a string, and the examples cover different scenarios like incorporating file checks before reading.
Python – Read File as String
You can read whole content of a file to a string in Python.
Generally, to read file content as a string, you follow these steps.
- Open file in read mode. Call inbuilt open() function with file path as argument. open() function returns a file object.
- Call read() method on the file object. read() method returns whole content of the file as a string.
- Close the file by calling close() method on the file object.
The default mode is text mode for open() function. So, even if you do not provide any mode for open() function, the read operation should work fine.
In the following examples, we write Python programs to read the text file given by a path, and store it as a string value.
1. Read file as a string
In this example, we assume that we a file with two lines of content present in the location
D:/data.txt. We shall apply the sequence of steps mentioned above, and read the whole content of file to a string.
#open text file in read mode text_file = open("D:/data.txt", "r") #read whole file to a string data = text_file.read() #close file text_file.close() print(data)
Hello World! Welcome to www.tutorialkart.com.
2. Negative scenario – File path incorrect while reading the file
In this example, we assume that we are trying to read content of a file that is not present. In other words, file path is incorrect.
#open text file in read mode text_file = open("D:/data123.txt", "r") #read whole file to a string data = text_file.read() #close file text_file.close() print(data)
Traceback (most recent call last): File "d:/workspace/fipics/rough.py", line 2, in <module> text_file = open("D:/data123.txt", "r") FileNotFoundError: [Errno 2] No such file or directory: 'D:/data123.txt'
There is our FileNotFoundError. And the message says that no such file or directory with the file path passed to open() function.
3. Check if file is present before reading file to a string
In this example, before reading a file, we shall check if the file present. Only after we make a confirmation that the file present, we shall read its content to a string.
To check if a file is present, we use os.path.isfile() function.
import os file_path = "D:/data123.txt" #check if file is present if os.path.isfile(file_path): #open text file in read mode text_file = open(file_path, "r") #read whole file to a string data = text_file.read() #close file text_file.close() print(data)
Now, try with the file paths that is present and not present. If the file is present, you read the text from file, else you don’t. But, no runtime error from Python Interpreter.
In this Python Tutorial, we learned how to read file content to a string.