[Tutor] Zipfile and File manipulation questions.

Chris Hengge pyro9219 at gmail.com
Sun Oct 15 03:34:55 CEST 2006


I was using afile.split("/"), but I'm not sure how to impliment it...

if "/" in afile: (for some reason I can't add 'or "\" in afile' on this
line)
                outfile = open(afile, 'w') # Open output buffer for writing.
(to open the file, I can't split here)
                outfile.write(zfile.read(afile)) # Write the file. (
zfile.read(afile)) wont work if I split here...)
                outfile.close() # Close the output file buffer.

On 10/14/06, Kent Johnson <kent37 at tds.net> wrote:
>
> Chris Hengge wrote:
> > Ok, last problem with this whole shebang...
> >
> > When I write the file from the zip, if it is in a subfolder, it will
> > error..
> > The code below will detect if the file in contained inside a directory
> > in the zip, but I just want it to write it like it wasn't.
> > Another words
> >
> > Zipfile.zip looks like this
> > file.ext
> > file2.ext
> > folder/
> >         anotherfile.ext
> >
> > file.ext extracts fine, file2.ext extracts file.. but it see's the last
> > file as folder/anotherfile.ext and it can't write it.. I tried to figure
> > out how to use .split to get it working right.. but I'm not having any
> > luck.. Thanks.
> >
> > 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('.cfg'):
> >             if afile.__contains__("/"):
>
> This should be spelled
>    if "/" in afile:
>
> __contains__() is the method used by the python runtime to implement
> 'in', generally you don't call double-underscore methods yourself.
>
> I think you want
>    afile = afile.rsplit('/', 1)[-1]
>
> that splits afile on the rightmost '/', if any, and keeps the rightmost
> piece. You don't need the test for '/' in afile, the split will work
> correctly whether the '/' is present or not.
>
> If you are on Windows you should be prepared for paths containing \ as
> well as /. You can use re.split() to split on either one.
>
> Kent
> >                 outfile = open(afile, '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.
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20061014/e198a93e/attachment.html 


More information about the Tutor mailing list