Files

Hopefully, most readers are familiar with the notion of files—named storage compartments on your computer that are managed by your operating system. Our last built-in object type provides a way to access those files inside Python programs. The built-in open function creates a Python file object, which serves as a link to a file residing on your machine. After calling open, you can read and write the associated external file, by calling file object methods.

Compared to types we’ve seen so far, file objects are somewhat unusual. They’re not numbers, sequences, or mappings; instead, they export methods only for common file processing tasks. Technically, files are a prebuilt C extension type that provides a thin wrapper over the underlying C stdio filesystem; in fact, file object methods have an almost 1-to-1 correspondence to file functions in the standard C library.

Table 2.10 summarizes common file operations. To open a file, a program calls the open function, with the external name first, followed by a processing mode ('r' means open for input, 'w' means create and open for output, 'a' means open for appending to the end, and others we’ll ignore here). Both arguments must be Python strings.

Table 2-10. Common File Operations

Operation

Interpretation

output = open('/tmp/spam', 'w')

Create output file ('w' means write)

input = open('data', 'r')

Create input file ('r' means read)

S = input.read()

Read entire file into a single string

S = input.read(N)

Read N bytes (1 ...

Get Learning Python 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.