Reading a file is as easy as writing from a file. To open a file for reading, we set the second parameter that is the access mode to "r" instead of "w". To read the data from this file, we use the read() method of the file handle object. Create a script called text_read.py and write the following content in it:
text_file = open("test.txt", "r")
data = text_file.read()
print(data)
text_file.close()
Following is the output:
student@ubuntu:~$ python3 text_read.py
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
In the preceding program, we've declared the text_file variable to open a file named test.txt. The open function takes two arguments: first, the file that we want to open, and second, the access mode that represents the permission or operation we want to do or apply on the file. In our program, we used the "r" letter in our second argument, which indicates a read operation. Then, we used text_file.close() to close the instance of the stored test.txt file. After running the Python program, we can easily see the content in our text file in our Terminal.