[Tutor] Zipfile and File manipulation questions.

Luke Paireepinart rabidpoobear at gmail.com
Tue Oct 17 17:27:13 CEST 2006


Kent Johnson wrote:
> Chris Hengge wrote:
>   
>> I chose the way I used the names because to me...
>>
>> outFile = open(aFile.lower(), 'w') # Open output buffer for writing.
>> = open a file with lowercase name for writing.
>> it is implied that aFile is from the zip, since it is created in the 
>> loop to read the zip..
>>
>> outFile.write(zFile.read(insideZip)) # Write the file.
>> = write what is read from inside the zip file.
>>     
>
> This sub-thread seems to have turned into "let's beat on Chris for the 
> way he names things" which certainly isn't what I intended. Ultimately 
> it is up to the program author to use the names that he thinks 
> communicate most clearly.
>   
Well, yes, and it's up to the auto mechanic to use the parts he thinks 
are best when he fixes your car.
However, one hopes that he has training in how to determine which parts 
are the most durable, safest, etc, etc.
Similarly, while it's up to you to choose variable names, we still hope 
that you know why you're choosing certain names.
> But I think the actual naming was secondary to the my main point which 
> is that the value for 'insideZip' is read from the zip, if you assign to 
> that name and keep it in that name the code is easier to follow because 
> the value that doesn't change stays in a name that doesn't change.
>
> So using your names, it would read
>              for insideZip in zFile.namelist():
>                  for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']:
>                      if insideZip .lower().endswith(ext):
>                          if "/" in insideZip :
>                            aFile = aFile.rsplit('/', 1)[-1]
>                          elif  "\\" in insideZip :
>                            aFile = aFile.rsplit('\\', 1)[-1]
>                          else:
>                            aFile = insideZip
>
> This way inzideZip is always the name from inside the zip, and aFile is 
> always the name of the file to write.
>   
I think it'd be most clear if you did something like:
ext = ['.cap','.hex','.fru','.cfg','.sdr']
for zipFile in zFile.namelist():
       if os.path.splitext(zipFile)[-1] in ext:
          outFile = os.path.split(zipFile)[-1]

but that's just me :)

I've gone back and read your code.
The problem Kent was pointing out was that your for loop was iterating 
over a variable called aFile,
and you were changing this variable during the loop.  This is generally 
considered Bad Practice.
That's all he meant.
I think.

HTH,
-Luke


More information about the Tutor mailing list