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

(yzsuai) #1
platforms. On output, binary mode accepts bytes and suppresses Unicode encod-
ing and line-end translations.

Manually closing files
This script also goes out of its way to manually close its files. As we also saw
in Chapter 4, we can often get by with a single line: open(partname,
'wb').write(chunk). This shorter form relies on the fact that the current Python
implementation automatically closes files for you when file objects are reclaimed
(i.e., when they are garbage collected, because there are no more references to the
file object). In this one-liner, the file object would be reclaimed immediately, be-
cause the open result is temporary in an expression and is never referenced by a
longer-lived name. Similarly, the input file is reclaimed when the split function
exits.
However, it’s not impossible that this automatic-close behavior may go away in
the future. Moreover, the Jython Java-based Python implementation does not re-
claim unreferenced objects as immediately as the standard Python. You should
close manually if you care about the Java port, your script may potentially create
many files in a short amount of time, and it may run on a machine that has a limit
on the number of open files per program. Because the split function in this module
is intended to be a general-purpose tool, it accommodates such worst-case
scenarios. Also see Chapter 4’s mention of the file context manager and the with
statement; this provides an alternative way to guarantee file closes.


Joining Files Portably


Back to moving big files around the house: after downloading a big game program file,
you can run the previous splitter script by clicking on its name in Windows Explorer
and typing filenames. After a split, simply copy each part file onto its own floppy (or
other more modern medium), walk the files to the destination machine, and re-create
the split output directory on the target computer by copying the part files. Finally, the
script in Example 6-6 is clicked or otherwise run to put the parts back together.


Example 6-6. PP4E\System\Filetools\join.py


#!/usr/bin/python
"""
################################################################################
join all part files in a dir created by split.py, to re-create file.
This is roughly like a 'cat fromdir/* > tofile' command on unix, but is
more portable and configurable, and exports the join operation as a
reusable function. Relies on sort order of filenames: must be same
length. Could extend split/join to pop up Tkinter file selectors.
################################################################################
"""


import os, sys
readsize = 1024


286 | Chapter 6: Complete System Programs

Free download pdf