[Tutor] Zipfile and File manipulation questions.
Kent Johnson
kent37 at tds.net
Mon Oct 16 20:41:25 CEST 2006
Chris Hengge wrote:
> Here is my solution, completed with (I think) all your suggestions...
>
> #########################################################################
> def extractZip(filePathName):
> """
> This method recieves the zip file name for decompression, placing the
> contents of the zip file appropriately.
> """
> if filePathName == "":
> print "No file provided...\n"
> else:
> try: # Attempt to unzip file.
> zFile = zipfile.ZipFile(filePathName.strip('"'), "r")
> for aFile in zFile.namelist(): # For every file in the zip.
> # If the file ends with a needed extension, extract it.
> for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']:
> if aFile.lower().endswith(ext):
> insideZip = aFile # Copy of Filename.
> if "/" in aFile: # Split the filename if '/'.
> aFile = aFile.rsplit('/', 1)[-1]
> elif "\\" in aFile: # Split the filename if '\'.
> aFile = aFile.rsplit('\\',
> 1)[-1]
> outfile = open( aFile.lower(), 'w') # Open
> output buffer for writing.
> outfile.write(zFile.read(insideZip)) # Write the
> file.
> outfile.close() # Close the output file buffer.
> print "Resource extraction completed successfully!\n"
> except IOerror, message: # If file creation fails, let the user
> know.
> print "File could not be written: \n"
> print message
>
> #########################################################################
> Definatly an improvement! Thanks Kent.
Yes, that is what I meant. One minor quibble, I think I would keep aFile
as the name in the zip, since that is what it starts as, and use a new
name for the external file name. Maybe you could use better names, for
example zipPath and fileName. I think that would make the code a little
clearer but it is a very minor point.
Kent
More information about the Tutor
mailing list