File input/output

In Python you can open and write in a file with:

  1. >>> file = open('myfile.txt', 'w')
  2. >>> file.write('hello world')
  3. >>> file.close()

Similarly, you can read back from the file with:

  1. >>> file = open('myfile.txt', 'r')
  2. >>> print file.read()
  3. hello world

Alternatively, you can read in binary mode with “rb”, write in binary mode with “wb”, and open the file in append mode “a”, using standard C notation.

The read command takes an optional argument, which is the number of bytes. You can also jump to any location in a file using seek.

You can read back from the file with read

  1. >>> print file.seek(6)
  2. >>> print file.read()
  3. world

and you can close the file with:

  1. >>> file.close()

In the standard distribution of Python, which is known as CPython, variables are reference-counted, including those holding file handles, so CPython knows that when the reference count of an open file handle decreases to zero, the file may be closed and the variable disposed. However, in other implementations of Python such as PyPy, garbage collection is used instead of reference counting, and this means that it is possible that there may accumulate too many open file handles at one time, resulting in an error before the gc has a chance to close and dispose of them all. Therefore it is best to explicitly close file handles when they are no longer needed. web2py provides two helper functions, read_file() and write_file() inside the gluon.fileutils namespace that encapsulate the file access and ensure that the file handles being used are properly closed.

When using web2py, you do not know where the current directory is, because it depends on how web2py is configured. The variable request.folder contains the path to the current application. Paths can be concatenated with the command os.path.join, discussed below.