Question 7.8: Reading from a File You need to read the contents of a file ......

Reading from a File

You need to read the contents of a file into a string variable.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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:
print(“Cannot open the file”)

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.

Related Answered Questions

Question: 7.14

Verified Answer:

Import sys and use its argv property, as shown in ...
Question: 7.15

Verified Answer:

Python has a library for the Simple Mail Transfer ...
Question: 7.13

Verified Answer:

Python has an extensive library for making HTTP re...
Question: 7.12

Verified Answer:

Use the random library: >>> import ran...
Question: 7.16

Verified Answer:

Use the bottle Python library to run a pure Python...
Question: 7.11

Verified Answer:

Use the import command: import random Discus...
Question: 7.7

Verified Answer:

Use the open, write, and close functions to open a...
Question: 7.6

Verified Answer:

Use inheritance to create a subclass of an existin...