Working with Python File Objects

Now we’ve had a good look at moving files around; it’s time to look inside them.

Python has a built-in file object, which is available on all Python platforms. Any Python program you hope to run on platforms other than Windows should use the standard file objects. Once you have a Python file object, you can use the methods to read data from the file, write data to the file, and perform various other operations.

Opening a file

The function open( filename , mode="r") returns a file object. If mode is omitted, the file is opened read-only. Mode is a string, and can be r for reading, w for writing, or a for appending. Add the letter b for binary (as discussed in Chapter 3), and w+ opens it for updating. See the Python Library Reference (included in HTML format in the standard Python distribution) for further details.

Table 17.3 shows the most important methods for file objects. C programmers will note the similarity to the STDIO routines; this should be no surprise, as they are implemented using the C STDIO routines of the same names.

Table 17.3. Methods of File Objects




Closes the file.


Flushes to disk. Windows caches disk activity; if you write a file, you can hear the lag between writing a file and the disk clicking. This ensures it’s written immediately.


Nonzero if the input is a terminal-type device (e.g., standard input when using Python from the console).


Reads up to [ size ] bytes ...

Get Python Programming On Win32 now with O’Reilly online learning.

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