Read a file
To read a file we’ve created in the previous lesson, we need to create a file object, but this time we will use the Read mode:
fr = open('new_file.txt', 'r')
We now need a variable to store the text inside the file. The read() method will to read the entire contents of new_file.txt and store it as one long string in the variable text:
text = fr.read()
We can then print the variable just like any other:
print(text)
>>>
Have a nice day!
You too!
>>>
Remember to close the file object after you are done working with it:
fr.close()
We can also read the file line by line using the for loop. This is how it is done:
fr = open('new_file.txt', 'r')
i = 1
for line in fr:
print(i, 'line:', line)
i += 1
fr.close()
The output:
1 line: Have a nice day! 2 line: You too!