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

(yzsuai) #1

Notice that the newer context managers feature discussed earlier could save us a few
lines here in the file-based filter of Example 4-3, and also guarantee immediate file
closures if the processing function fails with an exception:


def filter_files(name, function):
with open(name, 'r') as input, open(name + '.out', 'w') as output:
for line in input:
output.write(function(line)) # write the modified line

And again, file object line iterators could simplify the stream-based filter’s code in this
example as well:


def filter_stream(function):
for line in sys.stdin: # read by lines automatically
print(function(line), end='')

Since the standard streams are preopened for us, they’re often easier to use. When run
standalone, it simply parrots stdin to stdout:


C:\...\PP4E\System\Filetools> filters.py < hillbillies.txt
*Granny
+Jethro
*Elly May
+"Uncle Jed"

But this module is also useful when imported as a library (clients provide the line-
processing function):


>>> from filters import filter_files
>>> filter_files('hillbillies.txt', str.upper)
>>> print(open('hillbillies.txt.out').read())
*GRANNY
+JETHRO
*ELLY MAY
+"UNCLE JED"

We’ll see files in action often in the remainder of this book, especially in the more
complete and functional system examples of Chapter 6. First though, we turn to tools
for processing our files’ home.


Directory Tools


One of the more common tasks in the shell utilities domain is applying an operation
to a set of files in a directory—a “folder” in Windows-speak. By running a script on a
batch of files, we can automate (that is, script) tasks we might have to otherwise run
repeatedly by hand.


For instance, suppose you need to search all of your Python files in a development
directory for a global variable name (perhaps you’ve forgotten where it is used). There
are many platform-specific ways to do this (e.g., the find and grep commands in Unix),
but Python scripts that accomplish such tasks will work on every platform where Py-
thon works—Windows, Unix, Linux, Macintosh, and just about any other platform


Directory Tools | 163
Free download pdf