[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版
This call isn’t as commonly used (and can be emulated with a simple for loop or other iteration tool), but it is convenient in s ...
If closure is required, though, there are two basic alternatives: the try statement’s finally clause is the most general, since ...
For example, when the with statement block exits in the following, both files’ exit actions are automatically run to close the f ...
Let’s run these method calls to read files, lines, and characters from a text file—the seek(0) call is used here before each tes ...
Reading lines with file iterators In older versions of Python, the traditional way to read a file line by line in a for loop was ...
>>> file.__next__() 'Bye file world.\n' >>> file.__next__() Traceback (most recent call last): File "<stdin ...
defaults to r (input), and the buffering policy is to enable full buffering. For special needs, here are a few things you should ...
Binary and Text Files All of the preceding examples process simple text files, but Python scripts can also open and process file ...
b'Spam\n' >>> open('data.bin', 'wb').write('spam\n') TypeError: must be bytes or buffer, not str But notice that this f ...
to the encoding name passed in (or a default for the underlying platform: see sys.getdefaultencoding). Continuing our interactiv ...
>>> open('data.txt', 'rb').read() b'\xa2\x97\x81\x94\r%\x88\x81\x94\r%' If all your text is ASCII you generally can ign ...
translations listed previously could very well corrupt data as it is input or output—a random \r in data might be dropped on inp ...
>>> open('temp.bin', 'w').write(data.decode()) 8 >>> open('temp.bin', 'rb').read() # text mode write: added \r ...
at the contents of binary data in a structured way, though, as well as to construct its contents, the standard library struct mo ...
>>> number = bytes[8:10] >>> number b'\x00\x03' >>> struct.unpack('>h', number) (3,) Packed binary ...
>>> records = [bytes([char] * 8) for char in b'spam'] >>> records [b'ssssssss', b'pppppppp', b'aaaaaaaa', b'mm ...
'pppppppp' >>> file = open('random.bin', 'rb') # binary mode works the same here >>> file.seek(reclen * 2) # f ...
os.lseek( descriptor, position , how ) Moves to position in the file Technically, os calls process files by their descriptors, w ...
>>> file = open(r'C:\temp\spam.txt', 'w') # create external file, object >>> file.write('Hello stdio file\n') ...
But on some systems, os.open flags let us specify more advanced things like exclusive access (O_EXCL) and nonblocking modes (O_N ...
«
5
6
7
8
9
10
11
12
13
14
»
Free download pdf