Skip to Main Content
Python Programming On Win32
book

Python Programming On Win32

by Andy Robinson, Mark Hammond
January 2000
Intermediate to advanced content levelIntermediate to advanced
672 pages
21h 46m
English
O'Reilly Media, Inc.
Content preview from Python Programming On Win32

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Advanced Python Programming - Second Edition

Advanced Python Programming - Second Edition

Quan Nguyen

Publisher Resources

ISBN: 1565926218Supplemental ContentErrata Page