Reading from a File
You need to read the contents of a file into a string variable.
To read a file’s contents, you need to use the file methods open, read, and close. The following example reads the entire contents of the file into the variable s:
f = open(‘test.txt’) s = f.read() f.close() |
Discussion
You can also read text files one line at a time using the method readline.
The preceding example will throw an exception if the file does not exist or is not readable for some other reason. You can handle this by enclosing the code in a try/except construction like this:
try: f = open(‘test.txt’) s = f.read() f.close() except IOError: |
See Also
To write things to a file and for a list of file open modes, see Recipe 7.7.
For more information on handling exceptions, see Recipe 7.10.