[Tutor] Zipfile and File manipulation questions.
Bill Burns
billburns at pennswoods.net
Mon Oct 16 04:30:51 CEST 2006
Chris Hengge wrote:
> After getting some sleep and looking at my code, I think I was just to
> tired to work through that problem =P
>
> Here is my fully working and tested code..
> Thanks to you all for your assistance!
>
> if "/" in afile:
> aZipFile = afile.rsplit('/', 1)[-1] # Split file based on criteria.
> outfile = open(aZipFile, 'w') # Open output buffer for writing.
> outfile.write(zfile.read(afile)) # Write the file.
> outfile.close () # Close the output file buffer.
> elif "\\" in afile:
> aZipFile = afile.rsplit('\\', 1)[-1] # Split file based on criteria.
> outfile = open(aZipFile, 'w') # Open output buffer for writing.
> outfile.write(zfile.read(afile)) # Write the file.
> outfile.close() # Close the output file buffer.
> else:
> outfile = open(afile, 'w') # Open output buffer for writing.
> outfile.write(zfile.read(afile)) # Write the file.
> outfile.close() # Close the output file buffer.
Somewhere along the way, I got lost ;-) Why are you messing with the
slashes ("/" & "\\")?
If you're trying to split a path and filename, then your best bet is
'os.path.split()'.
For Example:
>>> import os
>>> s = '/some/path/to/file.txt'
>>> path, filename = os.path.split(s)
>>> path
'/some/path/to'
>>> filename
'file.txt'
'os.path.split()' works equally as well for paths containing "\\".
I have some code below which I *think* does what you want..... read a
zip file and 'write out' only those files with a certain file extension.
The directory structure is *not* preserved (it just writes all files to
the current working directory).
It has a little helper function 'myFileTest()' which I think makes
things easier ;-) The function tests a file to see if meets our
extension criteria.
HTH,
Bill
<code>
import zipfile
import os
# This is what I did for testing. Change it to point
# to your zip file...
zip = zipfile.ZipFile('test.zip', 'r')
def myFileTest(aFile):
"""myFileTest(aFile) -> returns True if input file
endswith one of the extensions specified below.
"""
for ext in ['.cap', '.hex', '.fru', '.cfg']:
if aFile.lower().endswith(ext):
return True
for aFile in zip.namelist():
# See if the file meets our criteria.
if myFileTest(aFile):
# Split the path and filename.
path, filename = os.path.split(aFile)
# Don't overwrite an existing file.
if not os.path.exists(filename):
# Write out the file.
outfile = open(filename, 'w')
outfile.write(zip.read(aFile))
outfile.close()
</code>
More information about the Tutor
mailing list