def join(fromdir, tofile):
output = open(tofile, 'wb')
parts = os.listdir(fromdir)
parts.sort()
for filename in parts:
filepath = os.path.join(fromdir, filename)
fileobj = open(filepath, 'rb')
while True:
filebytes = fileobj.read(readsize)
if not filebytes: break
output.write(filebytes)
fileobj.close()
output.close()
if name == 'main':
if len(sys.argv) == 2 and sys.argv[1] == '-help':
print('Use: join.py [from-dir-name to-file-name]')
else:
if len(sys.argv) != 3:
interactive = True
fromdir = input('Directory containing part files? ')
tofile = input('Name of file to be recreated? ')
else:
interactive = False
fromdir, tofile = sys.argv[1:]
absfrom, absto = map(os.path.abspath, [fromdir, tofile])
print('Joining', absfrom, 'to make', absto)
try:
join(fromdir, tofile)
except:
print('Error joining files:')
print(sys.exc_info()[0], sys.exc_info()[1])
else:
print('Join complete: see', absto)
if interactive: input('Press Enter key') # pause if clicked
Here is a join in progress on Windows, combining the split files we made a moment
ago; after running the join script, you still may need to run something like zip, gzip,
or tar to unpack an archive file unless it’s shipped as an executable, but at least the
original downloaded file is set to go‡:
C:\temp> python C:\...\PP4E\System\Filetools\join.py -help
Use: join.py [from-dir-name to-file-name]
‡ It turns out that the zip, gzip, and tar commands can all be replaced with pure Python code today, too. The
gzip module in the Python standard library provides tools for reading and writing compressed gzip files,
usually named with a .gz filename extension. It can serve as an all-Python equivalent of the standard gzip
and gunzip command-line utility programs. This built-in module uses another module called zlib that
implements gzip-compatible data compressions. In recent Python releases, the zipfile module can be
imported to make and use ZIP format archives (zip is an archive and compression format, gzip is a
compression scheme), and the tarfile module allows scripts to read and write tar archives. See the Python
library manual for details.
Splitting and Joining Files | 287