[Tutor] Zipfile and File manipulation questions.

Chris Hengge pyro9219 at gmail.com
Mon Oct 16 05:33:05 CEST 2006


The code in my last email that I stated worked, is doing exactly what I want
(perhaps there is a better method, but this is working)

The slash detection is for the subdirectories located inside of a zip file.
The name list for a file located inside a zipped folder shows up as
folder/file.ext in windows, and folder\file.ext in linux.. so I was
accounting for both. I dont think your method os.path.split() would work
since there isn't a fully qualified path coming from the namelist.

I like this little snip of code from your suggestion, and I may incorporate
it...

for ext in ['.cap', '.hex', '.fru', '.cfg']:
        if aFile.lower().endswith(ext):
            return True

Just for sake of sharing.. here is my entire method..

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:
        if filePathName[0] == '"': # If the path includes quotes, remove
them.
            zfile = zipfile.ZipFile(filePathName[1:-1], "r")
        else: # If the path doesn't include quotes, dont change.
            zfile = zipfile.ZipFile(filePathName, "r")
        for afile in zfile.namelist(): # For every file in the zip.
            # If the file ends with a needed extension, extract it.
            if afile.lower().endswith('.cap') \
            or afile.lower().endswith('.hex') \
            or afile.lower().endswith('.fru') \
            or afile.lower().endswith('.sdr') \
            or afile.lower().endswith('.cfg'):
                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.
        print "Resource extraction completed successfully!\n"

Not to go on and bore people with my project, the goal of this application
(which is nearly done) is to take several zip files that I've prompted the
user to drag and drop into the console, extract the necessary peices, add a
few more files, change some lines within a couple of the files extracted,
then pack it all back into one single zip... At this point, my little script
is doing everything other then the file i/o for changing the lines inside
the couple files needed (which I'll probably have done tomorrow if I have
time at work). The script does a little more then that, like sets up a file
structure and some menu's for the user, but essentially I've explained it...
and it takes about a 20-45minute job and chops it into less then 30
seconds.. And considering I run through this process sometimes dozens of
times a day, that time adds up fast.. Hopefully I can work on getting better
at coding python with my newly earned time =D

The flow of the script is a little odd because I had to make it extensible
by basically copying a method for a specific package I'm trying to build and
modifying to suite.. but.. once I'm fully done, this script should let me
add an entire new type of zip package within minutes.

Again, thanks to all of you for your input and suggestions.


On 10/15/06, Bill Burns <billburns at pennswoods.net> wrote:
>
> 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>
>
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20061015/39836c5d/attachment-0001.html 


More information about the Tutor mailing list