10.11: Reading from Files
- Page ID
To read the content of a file, pass the string 'r' instead of 'w' to the open() function. Then call the readlines() method on the file object to read in the contents of the file. Last, close the file by calling the close() method.
>>> textFile = open('hello.txt', 'r') >>> content = textFile.readlines() >>> textFile.close()
readlines() method returns a list of strings: one string for each line of text in the file:
>>> content ['This will be the content of the file.\n', 'Hello world!\n'] >>>
If you want to re-read the contents of that file, you will have to call
close() on the file object and re-open it.
As an alternative to
readlines(), you can also call the
read() method, which will return the entire contents of the file as a single string value:
>>> textFile = open('hello.txt', 'r') >>> content = textFile.read() >>> content 'This will be the content of the file.\nHello world!\n'
On a side note, if you leave out the second parameter to the
open() function, Python will assume you mean to open the file in read mode. So
open('foobar.txt', 'r') and
open('foobar.txt') do the exact same thing.