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

(yzsuai) #1
>>> file.__next__()
'Bye file world.\n'
>>> file.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

Interestingly, iterators are automatically used in all iteration contexts, including the
list constructor call, list comprehension expressions, map calls, and in membership
checks:


>>> open('data.txt').readlines() # always read lines
['Hello file world!\n', 'Bye file world.\n']

>>> list(open('data.txt')) # force line iteration
['Hello file world!\n', 'Bye file world.\n']

>>> lines = [line.rstrip() for line in open('data.txt')] # comprehension
>>> lines
['Hello file world!', 'Bye file world.']

>>> lines = [line.upper() for line in open('data.txt')] # arbitrary actions
>>> lines
['HELLO FILE WORLD!\n', 'BYE FILE WORLD.\n']

>>> list(map(str.split, open('data.txt'))) # apply a function
[['Hello', 'file', 'world!'], ['Bye', 'file', 'world.']]

>>> line = 'Hello file world!\n'
>>> line in open('data.txt') # line membership
True

Iterators may seem somewhat implicit at first glance, but they’re representative of the
many ways that Python makes developers’ lives easier over time.


Other open options


Besides the w and (default) r file open modes, most platforms support an a mode string,
meaning “append.” In this output mode, write methods add data to the end of the file,
and the open call will not erase the current contents of the file:


>>> file = open('data.txt', 'a') # open in append mode: doesn't erase
>>> file.write('The Life of Brian') # added at end of existing data
>>> file.close()
>>>
>>> open('data.txt').read() # open and read entire file
'Hello file world!\nBye file world.\nThe Life of Brian'

In fact, although most files are opened using the sorts of calls we just ran, open actually
supports additional arguments for more specific processing needs, the first three of
which are the most commonly used—the filename, the open mode, and a buffering
specification. All but the first of these are optional: if omitted, the open mode argument


144 | Chapter 4: File and Directory Tools

Free download pdf