[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
>>> file = open(r'C:\temp\spam.txt', 'w') # create external file, object
>>> file.write('Hello stdio file\n') # write via file object method
>>> file.flush() # else os.write to disk first!
>>> fd = file.fileno() # get descriptor from object
>>> fd
3
>>> import os
>>> os.write(fd, b'Hello descriptor file\n') # write via os module
>>> file.close()

C:\temp> type spam.txt # lines from both schemes
Hello stdio file
Hello descriptor file

os.open mode flags


So why the extra file tools in os? In short, they give more low-level control over file
processing. The built-in open function is easy to use, but it may be limited by the un-
derlying filesystem that it uses, and it adds extra behavior that we do not want. The
os module lets scripts be more specific—for example, the following opens a descriptor-
based file in read-write and binary modes by performing a binary “or” on two mode
flags exported by os:


>>> fdfile = os.open(r'C:\temp\spam.txt', (os.O_RDWR | os.O_BINARY))
>>> os.read(fdfile, 20)
b'Hello stdio file\r\nHe'

>>> os.lseek(fdfile, 0, 0) # go back to start of file
>>> os.read(fdfile, 100) # binary mode retains "\r\n"
b'Hello stdio file\r\nHello descriptor file\n'

>>> os.lseek(fdfile, 0, 0)
>>> os.write(fdfile, b'HELLO') # overwrite first 5 bytes
5

C:\temp> type spam.txt
HELLO stdio file
Hello descriptor file

In this case, binary mode strings rb+ and r+b in the basic open call are equivalent:


>>> file = open(r'C:\temp\spam.txt', 'rb+') # same but with open/objects
>>> file.read(20)
b'HELLO stdio file\r\nHe'
>>> file.seek(0)
>>> file.read(100)
b'HELLO stdio file\r\nHello descriptor file\n'
>>> file.seek(0)
>>> file.write(b'Jello')
5
>>> file.seek(0)
>>> file.read()
b'Jello stdio file\r\nHello descriptor file\n'

File Tools | 157
Free download pdf