Files (Python)

Being able to read and write files is important to nearly every type of program. In Python files are objects.

Basics

To open a file, we pass the filename as a string and whether we want to read or write to the open function, which returns a file object. For more details see the open function article.

Any file we read from must already exist, but if a file we try to write to doesn't exist Python will create it for us. Note also that by default Python only looks for files in the same directory as your program - make sure anything you want to use in your programs is saved there. If you create and save the file in IDLE this will be done automatically.

Reading

One common way to read an entire file is to use a for loop to loop through each line:

for line in myInFile:
    ...do stuff...

Alternately, you can use

line = myInFile.readline() 

to get one line at a time. Note that the l in readline is lowercase.

Note also that in either case the last character in the line will be the newline character '\n'. If you want to remove it you can use

line.strip()

Writing

To write to an output file we can use

myOutFile.write("This sentence will be written to the file.")

Note that, unlike when we print, write doesn't automatically append a newline character. Hence, you need to manually include '\n' whenever you want to end the current line, as seen below:

myOutFile.write("I like cake.\n")

Closing

When you're done writing to a file it's important that you close it by calling the close function:

myOutFile.close()

By default Python buffers your output and writes it to the file in large chunks. This is faster than writing smaller amounts more often, but it means your output might not actually appear in the file until you close it and Python flushes the buffers.

For files you read from closing isn't as important, but it's still good practice.

Useful Functions

In addition to readline, write, and close, the following methods might be useful.

  • outFile.flush() flushes the write buffer, if applicable. This is the same thing that happens when closing the file, but flush leaves the file open for more writing. You shouldn't usually have a need to call this method explicitly.
  • inFile.readlines() returns a list of all the lines remaining in the file.
  • outFile.writelines(linesList) writes the elements of linesList to the file. Note that newline characters still aren't inserted automatically, so you probably want to add them to the end of each element in the list yourself.

See Also

Python 3.2 Documentation