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

Method

Description

close()

Closes the file.

flush()

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.

isatty()

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

read([size])

Reads up to [ size ] bytes ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.