[Tutor] Zipfile and File manipulation questions.
Kent Johnson
kent37 at tds.net
Sun Oct 15 13:34:58 CEST 2006
Chris Hengge wrote:
> I was using afile.split("/"), but I'm not sure how to impliment it...
Did you see my hint below? Is there something you don't understand about it?
Kent
>
> 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 <mailto: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.
>
>
>
More information about the Tutor
mailing list