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

(yzsuai) #1
>>> records = [bytes([char] * 8) for char in b'spam']
>>> records
[b'ssssssss', b'pppppppp', b'aaaaaaaa', b'mmmmmmmm']

>>> file = open('random.bin', 'w+b')
>>> for rec in records: # write four records
... size = file.write(rec) # bytes for binary mode
...
>>> file.flush()
>>> pos = file.seek(0) # read entire file
>>> print(file.read())
b'ssssssssppppppppaaaaaaaammmmmmmm'

Now, let’s reopen our file in r+b mode; this mode allows both reads and writes again,
but does not initialize the file to be empty. This time, we seek and read in multiples of
the size of data items (“records”) stored, to both fetch and update them at random:


c:\temp> python
>>> file = open('random.bin', 'r+b')
>>> print(file.read()) # read entire file
b'ssssssssppppppppaaaaaaaammmmmmmm'

>>> record = b'X' * 8
>>> file.seek(0) # update first record
>>> file.write(record)
>>> file.seek(len(record) * 2) # update third record
>>> file.write(b'Y' * 8)

>>> file.seek(8)
>>> file.read(len(record)) # fetch second record
b'pppppppp'
>>> file.read(len(record)) # fetch next (third) record
b'YYYYYYYY'

>>> file.seek(0) # read entire file
>>> file.read()
b'XXXXXXXXppppppppYYYYYYYYmmmmmmmm'

c:\temp> type random.bin # the view outside Python
XXXXXXXXppppppppYYYYYYYYmmmmmmmm

Finally, keep in mind that seek can be used to achieve random access, even if it’s just
for input. The following seeks in multiples of record size to read (but not write) fixed-
length records at random. Notice that it also uses r text mode: since this data is simple
ASCII text bytes and has no line-ends, text and binary modes work the same on this
platform:


c:\temp> python
>>> file = open('random.bin', 'r') # text mode ok if no encoding/endlines
>>> reclen = 8
>>> file.seek(reclen * 3) # fetch record 4
>>> file.read(reclen)
'mmmmmmmm'
>>> file.seek(reclen * 1) # fetch record 2
>>> file.read(reclen)

154 | Chapter 4: File and Directory Tools

Free download pdf