Working with Files [June 5, 2011, 9:34 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()
  • readline() and readlines()
  • write()
  • seek()
  • close()
  • the Pickle module

open()

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

f = 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.

f.read()

readline() and readlines()

The readline() and readlines() methods read one and multiple lines of a file respectively.

readline() returns one line of the file as a string with a new line character ( '\n' ) at the end. If readline() returns an empty string, the end of the file has been reached.

>>> f.readline()

'This is the first line.\n'

>>> f.readline()

'This is the second line.\n'

>>> f.readline()

' '

readlines() returns all of the lines in a file as a list. Each line in the list will have a newline character ( '\n' ) at the end.

>>> f.readlines()

['This is the first line\n', 'This is the second line\n']

 

 

Learning Resources

Python for Informatics:

Python Docs