Re: [Tutor] Zipfile and File manipulation questions.
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. 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 guess for declaration it isn't very clear, but thats what comments are for? The comments about comments have been on the mark, I think. A helpful guideline I use is, when I think I need a comment, look at the names I am using and see if I can create a function whose name conveys what I wanted to say in the comment. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
I find your example rather amusing, since it makes it sound like you want this fictional mechanic to pick his parts by the brand name, rather then by how well the part works (in description vs context)... Your analogy seems to push that the brand name would inherently give the descriptive name which is fine.. Personally.. I dont care if you call it a motor or anything else... a motor is a motor because of its functionality... not because motor itself has some great descriptive meaning. We only understand what motor means because its been the standard to describe the hunk of metal, rubber, and plastic under the hook of an automobile. now.. if I've never heard of a motor... I'd learn what it is be getting some basic understanding of its functionality... it wouldn't matter what you called it if I've never heard the word, I'd have to know what it does to understand what distiguishes it from a bicycle. The only exception is when new terminology isn't defined for an object, such as motor-carriage(still have that darn motor word that I dont understand without knowing atleast basic functionality) or auto-mobile...(so... is this a bike that peddles itself? and flying machine? a cellphone that beams me to work automagically at 9:00am? We call them cars? why? because its what people stuck with from motor-'car'riage after adapting to the new machine.. You want to add to the mess... A truck is defined as a tool to move items around... mentally, I think of something more like a wheel-barrel.. but wait.. wheel-barrels dont look like barrels... either way... poor naming =P Names are nothing more then a distinguishing mark to define something that hasn't already been defined.. Humans are great because they wrap huge functional and contextual definitions to names and dont even realise it.. Think of your own name.. if that is all I used to describe you I'd never understand what was different between you and anyone else with your name.. but when I think of you( aka you in context), I can list tons of stuff that makes you who you are.. Try and imagine your name if I took it completely out of context and functionality... You'd have some name more like Brian, slacker of the eastside, teller of the great jokes, driver of the SUV, son of Marry and George, birth-father of little billy, owner of many pc's... vs the guy that lives in another neighborhood who'd have to be named Brian, civil servant of the eastside, impressor of women, driver of the sports car, Adopted,birth father to many across the town, owner of no pc's if you wanted to describe someone. Rambling aside... I was just trying to take a light hearted spin because the poor mechanic we have subjected for abuse in this debate struck me funny. On 10/17/06, Luke Paireepinart [EMAIL PROTECTED] wrote: 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 thinksare 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 hopethat 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 readfor 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 iteratingover 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___Tutor
Re: [Tutor] Zipfile and File manipulation questions.
I get what you are trying to say.. but I'm looking at the code after changing names, and I think it makes more sense in the code my way because of the following lines..outFile = open(aFile.lower(), 'w')#open 'afile' named with lowercase to 'w'rite outFile.write(zFile.read(insideZip))#write what you read 'insidezip' This is what I mean by functional names verses descriptive... Your way I'd have a better grasp of the data, my way I feel I have a better grasp of what is going on in my code. When I'm done writing my code and go back through the documentation I'll be adding all the variables used to the docstring, inputs, outputs.. all that jazz. Even if I didn't, and I'd never seen this code before, I'd try to figure out what it is doing before caring what data is being manipulated. Think about it... understanding the purpose in context will give me a better understanding of what the data going in, and coming out should appear to be, then hoping the author picked the right stuff. Perhaps I've adopted this habbit after years of trying to learn from snippets of code online where people use completely generic variable names as references, and kind of started ignoring variable names.. Seriously... its just how you look at things... I obviously read code and get my understanding very differently then many people on here. I take more of a top down approach, while it sounds many of you take a bottom up approach. On 10/17/06, Kent Johnson [EMAIL PROTECTED] 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 theway he names things which certainly isn't what I intended. Ultimatelyit is up to the program author to use the names that he thinks communicate most clearly.But I think the actual naming was secondary to the my main point whichis that the value for 'insideZip' is read from the zip, if you assign tothat 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 = insideZipThis way inzideZip is always the name from inside the zip, and aFile is always the name of the file to write. I guess for declaration it isn't very clear, but thats what comments are for?The comments about comments have been on the mark, I think. A helpful guideline I use is, when I think I need a comment, look at the names Iam using and see if I can create a function whose name conveys what Iwanted to say in the comment.Kent___ Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Chris Hengge wrote: 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.. Hopefully for the sake of feedback also... You have a lot of duplicated code that is pretty easy to remove, and a few places where there are easier ways to do it. In general duplicated code is a bad thing - it makes your program larger and harder maintain. Copy and paste is the enemy of readable, maintainable code. 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) I would write: filePathName = filePathName.strip('') 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'): The suggestion to use a loop here is excellent. If you are using Python 2.5 it's even easier: if afile.lower().endswith( ('.cap', '.hex', '.fru', '.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. Here you have three copies of the code to process the file. One way to avoid duplication is to factor duplicated code into a separate function but in this case I would preprocess afile, then do the work: if / in afile: afile = afile.rsplit('/', 1)[-1] elif \\ in afile: afile = afile.rsplit('\\', 1)[-1] You could do both of the above in one split using re.split() but I'm not sure you are ready for that... Now you can just use afile, it is the filename you want and you need only one copy of the following code: outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer. Kent print Resource extraction completed successfully!\n ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Excellent suggestions! I'll see how many of them I can impliment.Part of my project 'criteria' is that someone that doesn't know python (or possibly programming) should be able to follow my work to add a new system to the list. Right now I've got it setup so it only takes 3 steps. The reason for this is that I've inherited perl scripts that supposedly can do parts of what my project can do, except I dont know perl, and I dont want to either.. The language (atleast in these scripts) is VERY cryptic... no commenting, no implimentation for adding new output(which I have). This position is short term that high school interns tend to have, so I'm not going to be doing this very long, but it provided a great chance to work with a real world project for python, so I took it. As for python 2.5, I've not made the jump yet... I was waiting for active python to make their release... Not sure why, but this(active python) is what I'm used to =D. That, and I'm not sure how SPE will handle python 2.5 and from the feedback I've gotten from the author, he's not able to maintin his project at the moment, which is a shame. If I make changes based on your suggestions, I'll re-share the updated code incase anyone out there wants to see. On 10/16/06, Kent Johnson [EMAIL PROTECTED] wrote: Chris Hengge wrote: 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..Hopefully for the sake of feedback also...You have a lot of duplicated code that is pretty easy to remove, and a few places where there are easier ways to do it. In general duplicatedcode is a bad thing - it makes your program larger and harder maintain.Copy and paste is the enemy of readable, maintainable code. 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) I would write:filePathName = filePathName.strip('')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'):The suggestion to use a loop here is excellent. If you are using Python2.5 it's even easier:if afile.lower().endswith( ('.cap', '.hex', '.fru', '.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.Here you have three copies of the code to process the file. One way to avoid duplication is to factor duplicated code into a separate functionbut in this case I would preprocess afile, then do the work:if / in afile: afile = afile.rsplit('/', 1)[-1]elif\\ in afile: afile = afile.rsplit('\\', 1)[-1]You could do both of the above in one split using re.split() but I'm notsure you are ready for that...Now you can just use afile, it is the filename you want and you need only one copy of the following code:outfile = open(afile, 'w') # Open output buffer for writing.outfile.write(zfile.read(afile)) # Write the file.outfile.close() # Close the output file buffer. Kent print Resource extraction completed successfully!\n___Tutor maillist-Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Using one of the things you suggested... 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.Here you have three copies of the code to process the file. One way to avoid duplication is to factor duplicated code into a separate functionbut in this case I would preprocess afile, then do the work:if / in afile: afile = afile.rsplit('/', 1)[-1]elif\\ in afile: afile = afile.rsplit('\\', 1)[-1]##How do I account for the seperation I had? If you look closely... outfile = open(afile, 'w') # Open output buffer for writing. outfile.write(zfile.read(afile)) # Write the file. outfile.close() # Close the output file buffer.is not the same as: 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.The problem is, outfile.write(zfile.read(whatever)) 'whatever' must have the slashes in order to find the file I want inside the zip to extract.. 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. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
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.I guess for declaration it isn't very clear, but thats what comments are for?My naming was purely for my ease of mind.. I personally care less about what I call it when I declare, as to how it logically flows when I go to use it. I'm sure this is considered poor method, but once I declare a method I tend to never need to change the declaration, just how I use the info... I hope that makes sense. On 10/16/06, Kent Johnson [EMAIL PROTECTED] wrote: 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 newname for the external file name. Maybe you could use better names, forexample zipPath and fileName. I think that would make the code a little clearer but it is a very minor point.Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
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. I guess for declaration it isn't very clear, but thats what comments are for? No Consider the following 2 examples: #temp.py def aa(a): for b in range(2,a): if a % b == 0: return False return True a = int(raw_input('Please enter a prime number: ')) if not aa(a): print That's not a prime. raise SystemExit a = (2**a)-1 if aa(a): print It's a mersenne prime. else: print It's not a mersenne prime. # #Check_Mersenne_Numbers.py def isprime(candidate): for number in range(2,candidate): if number % candidate == 0: return False return True power = int(raw_input('Please enter a prime number: ')) if not isprime(power): print That's not a prime. raise SystemExit mersenne_number = (2**power) - 1 if not isprime(mersenne_number): print It's not a mersenne prime. else: print It is a mersenne prime. # Obviously, the whole aa(a) thing was designed to look ridiculous, but you have to remember that other people looking at your code don't know anything about it, like you do. You can comment the example #1 to the point where people can figure out what's going on, but example #2 is more or less completely clear as to what is happening at every step without any need for documentation. If you find yourself commenting Remember here that file is no longer the input file but is now the output file chances are you'd be better off having 2 variables, infile and outfile. If you fall into this pattern of willy-nilly naming variables you might someday have a script that looks like this: import os, sys print sys.argv sys = Intel Core 2 Duo os = Windows XP Professional print This computer is running %s on a(n) %s % (os,sys) #remember os and sys are strings and not modules #we need to use the os and sys modules again so we need to reimport them, #but we'll go ahead and import them as something else so we don't overwrite our string vars. import os as Os import sys as Sys if sys in Sys.argv: print They passed ,sys, as an argument! #we need an alternate configuration now SYs = AMD ATHLON 64 OS = Ubuntu #let's get the name of this script SYs = Os.path.split(Sys.argv[0])[-1] sys = Error creating directory. print this script is called %s % SYs #subdirectories for our oses try: Os.mkdir(OS) Os.mkdir(os) except: print sys #-- Haha. Just be forewarned! Coming up with good variable names is extremely important! My naming was purely for my ease of mind.. I personally care less about what I call it when I declare, as to how it logically flows when I go to use it. I'm sure this is considered poor method, but once I declare a method I tend to never need to change the declaration, just how I use the info... I hope that makes sense. No, I don't know what you mean here. On 10/16/06, *Kent Johnson* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: 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.
Re: [Tutor] Zipfile and File manipulation questions.
I didn't come up with those variable names willy nilly... I chose them because they reflect their functionality.. Which to me, is much more important then anything else... if I go back and look at code months later.. I have an easier time remember names based on functionality, and less of an easy time naming because that word best describes it real world example... I drive to work, I own a car... While car is the actual object description, when I go to tell someone what I'm attempting to do with the car, 'drive' is much more clear then car. On 10/16/06, Luke Paireepinart [EMAIL PROTECTED] 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. I guess for declaration it isn't very clear, but thats what comments are for?NoConsider the following 2 examples:#temp.pydef aa(a):for b in range(2,a):if a % b == 0: return Falsereturn Truea = int(raw_input('Please enter a prime number: '))if not aa(a):print That's not a prime.raise SystemExita = (2**a)-1if aa(a): print It's a mersenne prime.else:print It's not a mersenne prime.##Check_Mersenne_Numbers.pydef isprime(candidate):for number in range(2,candidate): if number % candidate == 0:return Falsereturn Truepower = int(raw_input('Please enter a prime number: '))if not isprime(power):print That's not a prime. raise SystemExitmersenne_number = (2**power) - 1if not isprime(mersenne_number):print It's not a mersenne prime.else:print It is a mersenne prime.# Obviously, the whole aa(a) thing was designed to look ridiculous,but you have to remember that other people looking at your code don'tknow anything about it, like you do.You can comment the example #1 to the point where people can figure out what's going on,but example #2 is more or less completely clear as to what is happeningat every step without any need for documentation.If you find yourself commenting Remember here that file is no longer the input file but is now the output filechances are you'd be better off having 2 variables, infile and outfile.If you fall into this pattern of willy-nilly naming variables you mightsomeday have a script that looks like this: import os, sysprint sys.argvsys = Intel Core 2 Duoos = Windows XP Professionalprint This computer is running %s on a(n) %s % (os,sys) #remember osand sys are strings and not modules #we need to use the os and sys modules again so we need to reimport them,#but we'll go ahead and import them as something else so we don'toverwrite our string vars.import os as Osimport sys as Sys if sys in Sys.argv: print They passed ,sys, as an argument!#we need an alternate configuration nowSYs = AMD ATHLON 64OS = Ubuntu#let's get the name of this script SYs = Os.path.split(Sys.argv[0])[-1]sys = Error creating directory.print this script is called %s % SYs#subdirectories for our osestry:Os.mkdir(OS)Os.mkdir(os) except:print sys#--Haha.Just be forewarned!Coming up with good variable names is extremelyimportant! My naming was purely for my ease of mind.. I personally care less about what I call it when I declare, as to how it logically flows when I go to use it. I'm sure this is considered poor method, but once I declare a method I tend to never need to change the declaration, just how I use the info... I hope that makes sense.No, I don't know what you mean here. On 10/16/06, *Kent Johnson* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: 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 #
Re: [Tutor] Zipfile and File manipulation questions.
Chris Hengge wrote: I didn't come up with those variable names willy nilly... I know :) I just wanted to make it clear that your statement 'that's what comments are for' wasn't really a good way to look at it. If you have to write a comment because your usage of variables, or something else you're doing, contradicts what someone would logically think you're trying to accomplish, then it's bad. If you're writing a comment to explain an algorithm or something you're doing, it's good. I chose them because they reflect their functionality.. Which to me, is much more important then anything else... if I go back and look at code months later.. I have an easier time remember names based on functionality, and less of an easy time naming because that word best describes it That's perfectly fine... but also, if you're using a single variable for multiple things, you might get confused about what it is at a certain point... and if you have to trace back up through your code and figure out where you modified the variable, it's less convenient. You know what I mean? I actually read kent's comment 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. and I didn't read your code, and I think I misunderstood what Kent meant. So you probably have no idea what I'm talking about. Oh well, sorry! real world example... I drive to work, I own a car... While car is the actual object description, when I go to tell someone what I'm attempting to do with the car, 'drive' is much more clear then car. Yeah, that makes sense, but I'm not really sure how it applies in this case. -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
[quote]and I didn't read your code[/quote]How's that supposed to help? =D ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Zipfile and File manipulation questions.
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. I guess for declaration it isn't very clear, but thats what comments are for? My naming was purely for my ease of mind.. I personally care less about what I call it when I declare, as to how it logically flows when I go to use it. I'm sure this is considered poor method, but once I declare a method I tend to never need to change the declaration, just how I use the info... I hope that makes sense. Even if you're the only person that EVER lays eyes on that code (and you inherited Perl code, so I assume someone will eventually take this code over) it's vital to use names that are clear and concise. If you disagree, put your code away in a locked box, then re-read it after six months and see if it makes perfect sense. As Kent said, this is quite a minor issue that shouldn't be paraded, but I have been on the receiving end of code such as: int a; if (a == 0) { /* do something interesting */ } else { /* do something less interesting */ } (Sorry for the Java-ish flair...Java happens to be on my mind at the moment...) Even if I was there when the code was written, how could I know what a means a month later without digging back through to see how it's used? (and worse, a was used for conditional testing in this specific example (i.e. on/off conditions), so a boolean would have done MUCH better). Commenting can only help so much...the code must speak for itself at some point. (Yes, I know this is an extreme example, but it happens all the time). Something like this is much more readable: boolean fileExists; if (fileExists) { /* do something interesting */ } else { /* do something less interesting */ } I'm not complaining, because afterall it's up to you to write the code you're comfortable with (because you're not working on a team, that is), but a friendly suggestion on naming conventions (especially when you can refactor in most IDE's today) could go a long ways to helping you build readable code that is easier to maintain. Jonathon On 10/16/06, *Kent Johnson* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: 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 ___ Tutor maillist -
Re: [Tutor] Zipfile and File manipulation questions.
Have you even read my code to see if you find it cryptic? I'm starting to beleive people just read the one comment on possibly using better naming conventions and assumed I had picked completely irrelivent names. On 10/16/06, Jonathon Sisson [EMAIL PROTECTED] 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. I guess for declaration it isn't very clear, but thats what comments are for? My naming was purely for my ease of mind.. I personally care less about what I call it when I declare, as to how it logically flows when I go to use it. I'm sure this is considered poor method, but once I declare a method I tend to never need to change the declaration, just how I use the info... I hope that makes sense.Even if you're the only person that EVER lays eyes on that code (and you inherited Perl code, so I assume someone will eventually take this codeover) it's vital to use names that are clear and concise.If youdisagree, put your code away in a locked box, then re-read it after six months and see if it makes perfect sense.As Kent said, this is quite a minor issue that shouldn't be paraded, butI have been on the receiving end of code such as:int a;if (a == 0){/* do something interesting */ }else{/* do something less interesting */}(Sorry for the Java-ish flair...Java happens to be on my mind at themoment...)Even if I was there when the code was written, how could I know what a means a month later without digging back through to see how it's used?(and worse, a was used for conditional testingin this specificexample (i.e. on/off conditions), so a boolean would have done MUCH better).Commenting can only help so much...the code must speak foritself at some point.(Yes, I know this is an extreme example, but ithappens all the time).Something like this is much more readable: boolean fileExists;if (fileExists){/* do something interesting */}else{/* do something less interesting */}I'm not complaining, because afterall it's up to you to write the code you're comfortable with (because you're not working on a team, that is),but a friendly suggestion on naming conventions (especially when you canrefactor in most IDE's today) could go a long ways to helping you build readable code that is easier to maintain.Jonathon On 10/16/06, *Kent Johnson* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] wrote: 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 ___ Tutor maillist- Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Chris Hengge wrote: Have you even read my code to see if you find it cryptic? I'm starting to beleive people just read the one comment on possibly using better naming conventions and assumed I had picked completely irrelivent names. Well, Chris, what can I say? We're busy people and we generally assume that Kent knows what he's talking about ;) I'll read your code sometime but I have to take care of some Calculus homework right now! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
On Mon, 16 Oct 2006, Chris Hengge wrote: Have you even read my code to see if you find it cryptic? I'm starting to beleive people just read the one comment on possibly using better naming conventions and assumed I had picked completely irrelivent names. Hi Chris, Sometimes one of us (or a few of us) might rush out our answers a bit too quickly. I think we're just trying to make good on that 24 hours or your answer is free thing. *wink* The last version I've seen of your code is: http://mail.python.org/pipermail/tutor/2006-October/050059.html The comment I'd make on extractZip is that it is a bit nested and long. You might want to apply a refactoring to flatten things out a bit. Concretely, if we look at extractZip(): ### def extractZip(filename): ... zFile = zipfile.ZipFile(filePathName.strip(''), r) for aFile in zFile.namelist(): for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: if aFile.lower().endswith(ext): ... we see that it has several levels of logic. But it can have its nesting reduced if we provide a helper function to recognize interesting filenames: def isInterestingFile(fileName): Returns True if the fileName ends with a needed extension, and False otherwise. for ext in ['.cap', '.hex', '.fru', '.cfg', '.sdr']: if fileName.lower().endswith(ext): return True return False If we have this isInterestingFile() as a helper function, the main logic in extractZip is easier to see: # def extractZip(filename): ... zFile = zipfile.ZipFile(filePathName.strip(''), r) for aFile in zFile.namelist(): if isInterestingFile(aFile): ... # Since the helper function is standalone, it's just physically easier to see that what's distinguishing interesting files from non-interesting ones is its treatment of the extension, and I hope you agree that the structure of extractZip() improves a bit. You may want to consider restructuring your program like this, using things like helper functions, so that commenting every single line of code becomes less necessary to understand the program. As it stands, every line of code is commented --- this is usually overkill. If you find yourself needing to do it to understand the program, consider the possiblity that those comments might be acting as a crutch. The approach that most of us here recommend is to simplify the program structure so that it's easy to understand. Comments are necessary, but they should be used judiciously. See how far you can get by using helper functions to break out blocks of interesting and useful code. If you want another example of a possible refactoring, feel free to ask the group. Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
On 10/14/06, Chris Hengge [EMAIL PROTECTED] wrote: Guess nobody has had a chance to point me in the write direction on this problem yet?Thats ok, I've gotten a ton of other code written, and I'll come back to this tricky part later.This particular project I've been working on to automate some of my job at work has been an excellent learning experience. :D On 10/14/06, Chris Hengge [EMAIL PROTECTED] wrote: I was using afile.split(/), but I'm not sure how to impliment it... I think kent johnson gave you a solution to this...was it not acceptable? Another alternate route you can take is os.path.split(path)[-1]this will give you the filename no matter what system you're on.it should work for '\\' and '/'.Are you making a script to automatically unzip something? ( I confess, I didn't read the other e-mails before this one.)If you are, and the problem you're having is with writing files to subdirectories,you'd want to do something like this:check if directory you want exists if it does, change into it.if it doesn't, create it and then change into it.recursively do this until you get to where you want to create the file...then create the file you want.in python, this would look like: import ospath = 'directory/subdir/filename.txt' #this is the path you use from your zipfile or w/epath = os.path.split(path) #this will make a list ['directory','subdir','filename.txt']for item in path[:-1]: #everything but the last item (which is the filename) if item not in os.listdir(): #directory doesn't exist os.mkdir(item)#so we'll create it os.chdir(item)#it doesn't matter to us if the directory exists before, we change into it either way. f = file(path[-1])#create the file you wantedf.write(Hello, this is the file)#change this to write the file info from out of the zip.f.close()#close file :)#now let's go back to the parent directory so we don't get lost later on :) for x in path[:-1]:#for every directory that we've changed into, os.chdir('..') #go back to parent directory.I don't have a python interp installed on this computer, so there may be errors,and if so, I apologize in advance, but I can't see any reason why this wouldn't work. I just realized os.path doesn't do what I thought it does. It only splits the end.so I guess my solution above would work, but you'd have to split it a different way :)I hope that helps,-Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
I must have not been clear.. I have a zip file with folders inside.. When I extract it.. I dont want the folder structure, just the files.. using split doesn't seem to help in this situation.. unless I'm not putting the results in the right spot.. Thanks again though. On 10/15/06, Luke Paireepinart [EMAIL PROTECTED] wrote: On 10/14/06, Chris Hengge [EMAIL PROTECTED] wrote: Guess nobody has had a chance to point me in the write direction on this problem yet?Thats ok, I've gotten a ton of other code written, and I'll come back to this tricky part later.This particular project I've been working on to automate some of my job at work has been an excellent learning experience. :D On 10/14/06, Chris Hengge [EMAIL PROTECTED] wrote: I was using afile.split(/), but I'm not sure how to impliment it... I think kent johnson gave you a solution to this...was it not acceptable? Another alternate route you can take is os.path.split(path)[-1]this will give you the filename no matter what system you're on.it should work for '\\' and '/'.Are you making a script to automatically unzip something? ( I confess, I didn't read the other e-mails before this one.)If you are, and the problem you're having is with writing files to subdirectories,you'd want to do something like this:check if directory you want exists if it does, change into it.if it doesn't, create it and then change into it.recursively do this until you get to where you want to create the file...then create the file you want.in python, this would look like: import ospath = 'directory/subdir/filename.txt' #this is the path you use from your zipfile or w/epath = os.path.split(path) #this will make a list ['directory','subdir','filename.txt']for item in path[:-1]: #everything but the last item (which is the filename) if item not in os.listdir(): #directory doesn't exist os.mkdir(item)#so we'll create it os.chdir(item)#it doesn't matter to us if the directory exists before, we change into it either way. f = file(path[-1])#create the file you wantedf.write(Hello, this is the file)#change this to write the file info from out of the zip.f.close()#close file :)#now let's go back to the parent directory so we don't get lost later on :) for x in path[:-1]:#for every directory that we've changed into, os.chdir('..') #go back to parent directory.I don't have a python interp installed on this computer, so there may be errors, and if so, I apologize in advance, but I can't see any reason why this wouldn't work. I just realized os.path doesn't do what I thought it does. It only splits the end.so I guess my solution above would work, but you'd have to split it a different way :)I hope that helps,-Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Chris Hengge wrote: I must have not been clear.. I have a zip file with folders inside.. When I extract it.. I dont want the folder structure, just the files.. using split doesn't seem to help in this situation.. unless I'm not putting the results in the right spot.. Can you show us what you tried? split() can definitely help here. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
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* [EMAIL PROTECTED] mailto:[EMAIL PROTECTED] 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. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
After getting some sleep and looking at my code, I think I was just to tired to work through that problem =PHere 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.On 10/15/06, Kent Johnson [EMAIL PROTECTED] wrote:Chris Hengge wrote: I must have not been clear.. I have a zip file with folders inside.. When I extract it.. I dont want the folder structure, just the files.. using split doesn't seem to help in this situation.. unless I'm not putting the results in the right spot..Can you show us what you tried? split() can definitely help here. Kent___Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
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 TrueJust 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 [EMAIL PROTECTED] 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 theslashes (/ \\)?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 azip file and 'write out' only those files with a certain file extension. The directory structure is *not* preserved (it just writes all files tothe current working directory).It has a little helper function
Re: [Tutor] Zipfile and File manipulation questions.
Bill Burns wrote: Maybe take a look at 'endswith': Example: for filename in zfile.namelist(): if filename.endswith('.exe') or filename.endswith('.txt'): # do something with filename In Python 2.5 endswith() can take a tuple of strings to try: if filename.endswith(('.exe', '.txt')): (The double parentheses create a single, tuple argument instead of passing two string arguments.) And yes, endswith() is case-sensitive; use e.g. if filename.lower().endswith(('.exe', '.txt')): Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Oops I get an error using that code.. if filename.endswith('.cap','.fru','.hex') or filename.endswith('.sdr', '.cfg'):TypeError: slice indices must be integers or None On 10/14/06, Bill Burns [EMAIL PROTECTED] wrote: Chris Hengge wrote: First question.. This is the code that I have: for filename in zfile.namelist(): outfile = open(filename, 'w') outfile.write(zfile.read(filename)) outfile.close() Is there a way to say : for filename in zfile.namelist() contains '.txt, .exe': outfile = open(filename, 'w') outfile.write(zfile.read (filename)) outfile.close()Maybe take a look at 'endswith':Example:for filename in zfile.namelist(): if filename.endswith('.exe') or filename.endswith('.txt'): # do something with filename second question is along the same lines.. I'm looking for a way to say: os.remove('All by .py') or- os.remove('*.txt, *.exe') Thank you all again for your time and effort. ___ Tutor maillist- Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Chris Hengge wrote: Oops I get an error using that code.. if filename.endswith('.cap','.fru','.hex') or filename.endswith('.sdr', '.cfg'): TypeError: slice indices must be integers or None With Python 2.5 you can do this with a tuple argument. You need an extra set of parentheses to create the tuple: if filename.endswith(('.cap','.fru','.hex', '.sdr', '.cfg')): In Python 2.4 or less you need a separate endswith() for each ending. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Got that working now, thanks. I've been using activepythons release, and they dont have 2.5 prepared yet. Guess I should just upgrade without them?On 10/14/06, Kent Johnson [EMAIL PROTECTED] wrote:Chris Hengge wrote: Oops I get an error using that code.. if filename.endswith('.cap','.fru','.hex') or filename.endswith('.sdr', '.cfg'): TypeError: slice indices must be integers or None With Python 2.5 you can do this with a tuple argument. You need an extraset of parentheses to create the tuple:if filename.endswith(('.cap','.fru','.hex', '.sdr', '.cfg')):In Python 2.4 or less you need a separate endswith() for each ending. Kent___Tutor maillist-Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
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 wordsZipfile.zip looks like thisfile.extfile2.extfolder/ anotherfile.extfile.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__(/): 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.On 10/14/06, Chris Hengge [EMAIL PROTECTED] wrote:Got that working now, thanks. I've been using activepythons release, and they dont have 2.5 prepared yet. Guess I should just upgrade without them?On 10/14/06, Kent Johnson [EMAIL PROTECTED] wrote: Chris Hengge wrote: Oops I get an error using that code.. if filename.endswith('.cap','.fru','.hex') or filename.endswith('.sdr', '.cfg'): TypeError: slice indices must be integers or None With Python 2.5 you can do this with a tuple argument. You need an extraset of parentheses to create the tuple:if filename.endswith(('.cap','.fru','.hex', '.sdr', '.cfg')):In Python 2.4 or less you need a separate endswith() for each ending. Kent___Tutor maillist-Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
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. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
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 [EMAIL PROTECTED] 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 rightmostpiece. You don't need the test for '/' in afile, the split will workcorrectly whether the '/' is present or not. If you are on Windows you should be prepared for paths containing \ aswell 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. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Correction... The first comment I just realised I needed \\ to make it work.. so that issue is gone.. On 10/14/06, Chris Hengge [EMAIL PROTECTED] wrote: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 [EMAIL PROTECTED] 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 rightmostpiece. You don't need the test for '/' in afile, the split will workcorrectly whether the '/' is present or not. If you are on Windows you should be prepared for paths containing \ aswell 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. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Guess nobody has had a chance to point me in the write direction on this problem yet?Thats ok, I've gotten a ton of other code written, and I'll come back to this tricky part later.This particular project I've been working on to automate some of my job at work has been an excellent learning experience. :D On 10/14/06, Chris Hengge [EMAIL PROTECTED] wrote: 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 [EMAIL PROTECTED] 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 rightmostpiece. You don't need the test for '/' in afile, the split will workcorrectly whether the '/' is present or not. If you are on Windows you should be prepared for paths containing \ aswell 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. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Zipfile and File manipulation questions.
First question..This is the code that I have:for filename in zfile.namelist(): outfile = open(filename, 'w') outfile.write(zfile.read(filename)) outfile.close()Is there a way to say : for filename in zfile.namelist() contains '.txt, .exe': outfile = open(filename, 'w') outfile.write(zfile.read(filename)) outfile.close()second question is along the same lines.. I'm looking for a way to say:os.remove('All by .py')or-os.remove('*.txt, *.exe')Thank you all again for your time and effort. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Is there a way to say : for filename in zfile.namelist() contains '.txt, .exe': Hi Chris, Yes. It sounds like you want to filter zfile.namelist() and restrict the entries to those with particular extensions. Try a list comprehension to filter for those interesting filenames: for filename in [f for f in zfile.namelist() if os.path.splitext(f)[1] in ('.txt', '.exe')]: This may be a little dense and hard to read. So you can always break this out into a function: # def keep_txt_exe_filenames(file_list): keep_txt_exe_filenames: list of strings - list of strings Returns a list of all filenames that end in .txt or .exe. return [f for f in file_list if os.path.splitext(f)[1] in ('.txt', '.exe')] # At least that tight expression is documented and can be treated as a black box. But after you have this function, you can use that helper function: for filename in keep_txt_exe_filenames(zfile.namelist()): ... which is usually fairly easy for a person to understand. os.remove('*.txt, *.exe') One way to approach this is with loops. You might find the glob module useful here: http://docs.python.org/lib/module-glob.html It'll help to match the file names for each glob pattern. Again, if you find yourself doing this a bit, make a helper function to make it easier to say next time. *grin* Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor