26.12. File Operations

One of the advantages of using CGI programs is that they can read and write to the filesystem, and Python is no exception. Python includes quite a few functions for dealing with file IO, which are covered in the following sections.

26.12.1. Standard Operating Procedure

To access files, there are three operations that you need to perform:

  1. Open the file and assign a file handle.

  2. Perform file operations (read/write/append).

  3. Close the file handle, thereby closing the open file.

26.12.2. Opening a File

To open a file, Python uses the open function. The open function has the following syntax:

FILEHANDLE=open("filename",mode)

For example, to open the file test.txt, you would use code similar to the following:

try:
   FILEHANDLE = open('/tmp/filename.txt', 'r')
except IOError:
   print 'cannot open file.'

The preceding syntax will result in the script exiting and displaying "cannot open file" if the open function does not succeed.

The preceding syntax will result in the script exiting and displaying "cannot open file" if the open function does not succeed. The FILEHANDLE can be any valid variable name but should be descriptive enough to be easily identified as a file handle. One standard practice is to capitalize the file handle variables.

The default operation of the open function is to open a file for reading. To open a file for writing you need to specify a mode of 'w'; to append to a file you would specify a mode of 'a'; to open the file read-only you would specify ...

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.