Skip to main content

10.2) File Reading And Writing


Reading or writing to a file in Python (as in many languages) involves three steps: (i) opening the file, (ii) Reading or writing content, (iii) closing the file. Here are some examples:

f=open('/path/to/file/file.txt','r')    # 'r' is for 'reading'
content=f.read()
f.close()
print content

Create a file with a few lines of text and call it file.txt. Write the code above in a program and execute it in IDLE so that it reads in your newly created file.txt. Important, if Python has trouble finding your file, write the full path to the file, for example:

f=open(r'C:\Users\Lauren\Desktop\file.txt')

Remember that backslash (\) is a special character. To avoid issues with paths on Windows, use raw strings (precede your string with r).

content is a string with all the content of the file. Lines are separated by the special character newline: '\n'

Replace f.read() with f.readlines():

content=f.readlines()

This time, content is a list of strings with the individual lines of the file you read. At the end of each string (or line) is the special character newline \n.

Replace f.readlines() with f.readline(), without the 's'!:

line=f.readline()

This will read one line and advance the placeholder associated with f to the next line. So that if you then add to your program (before the f.close() line):

line2=f.readline()

It reads the second line.