Files

You may already be familiar with the notion of files, which are named storage compartments on your computer that are managed by your operating system. The last major built-in object type that we’ll examine on our object types tour provides a way to access those files inside Python programs.

In short, 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 transfer strings of data to and from the associated external file by calling the returned file object’s methods.

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Compared to the types you’ve seen so far, file objects are somewhat unusual. They’re not numbers, sequences, or mappings, and they don’t respond to expression operators; they export only methods for common file-processing tasks. Most file methods are concerned with performing input from and output to the external file associated with a file object, but other file methods allow us to seek to a new position in the file, flush output buffers, and so on. Table 9-2 summarizes common file operations.

Table 9-2. Common file operations

Operation

Interpretation

output = open(r'C:\spam', 'w')

Create output file ('w' means write)

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

Create input file ('r' means read)

input = open('data')

Same as prior line ('r' is the default)

aString = input.read()

Read entire file into a single string

aString = input.read(N)

Read up to next N characters (or bytes) into a string

aString = input.readline()

Read next line (including \n newline) into a string

aList = input.readlines()

Read entire file into list of line strings (with \n)

output.write(aString)

Write a string of characters (or bytes) into file

output.writelines(aList)

Write all line strings in a list into file

output.close()

Manual close (done for you when file is collected)

output.flush()

Flush output buffer to disk without closing

anyFile.seek(N)

Change file position to offset N for next operation

for line in open('data'): use line

File iterators read line by line

open('f.txt', encoding='latin-1')

Python 3.0 Unicode text files (str strings)

open('f.bin', 'rb')

Python 3.0 binary bytes files (bytes strings)