This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Working with Files [June 5, 2011, 9:14 p.m.]



An important part of programming is knowing how to work directly with files. Lets review the following Pythonic tools for working with files:

  • open()
  • read()
  • readlines()
  • write()
  • seek()
  • close()
  • the Pickle module

open()

The open() function takes a filename and path as input and returns a file object.

open('/path/to/file', 'r')

The second parameter for the open() function is the file permission mode and is entered in the form of read (r), write (w), or append (a). If no mode parameter is passed, the mode defaults to read. To open binary files, append 'b' to the mode parameter, e.g. read binary ('rb').

read()

The read() method will return the contents of the file as a string. Be careful that your computer has enough memory to read the entire file at once. read() accepts an optional parameter called 'size' that restricts Python to reading a specific portion of the file.

 

Learning Resources

Python for Informatics:

Python Docs