Lesson 8
Making Objects the Main Star!
Chapter 9: Reading and writing files
Opening and reading text files
You have already opened text files using the open() built-in function.
file = open("test.txt", "r")
for line in file:
print(line.strip())
When you open a file using the open() function, it returns a file object that is used to read and modify the file.
By default, Python opens a file in read-only mode ("r"). Thus, you can omit the second mode argument "r" if you are only reading the file (as we have done so far).
I have also introduced the .readlines() method that reads in all lines into a list.
file = open("test.txt", "r")
lines = file.readlines()
for line in lines:
print(line.strip())
You can also use the .read() method to return the content of the whole file as a single str. Not recommended if the file is large!
file = open("test.txt")
content = file.read()
print(content)
If you want even more fine-grained control, you can use .read(n) to read only n characters, or .readline() to read one line. If you call .read(n) again, it will return the next n characters. For .readline(), it will be the next line. Once it reaches the end of the file, it will just return an empty string.
You should think of a file as a ‘pointer’ that keeps track of its current position in the file. The ‘pointer’ can be moved around to any position in the file.