Re: [Tutor] How to read content in a tar file with tarfile module
Thank you for all the answers. Sorry for not replying but i have been very busy this week I will try all the suggested ways. //Magnus Magnus Wirström skrev: > Hi everyone > > I have written a app that makes a tar file and all works well... Now i > want to expand that app so it can read read the tar and give me the > contents of the tar file. How is the best way to do this ? I can't find > a "listdir" like function in tarfile. Can anyone point me in the right > direction? > Thanks > Magnus > ___ > 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] tkinter tutorials
> Danny, "Python and Tkinter Programming" is still in its first > edition, which came out in 2000. Python has changed a lot since > then. > Hasn't Tkinter? Is the book still usable by a Tkinter beginner? Tkinter has not changed hardly at all. The only shame about the book is that it strongly features the Python MegaWidgets add-on library whereas it was Tix that was adoptted in the standard library, and there is no coverage of Tix at all. (Time for a second edition Manning?) However the book is not really a beginners book in Tkinter, you should do Fred Lundh's intro tutorial first, but it is good on more advanced topics and as a reference book. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
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] tkinter tutorials
"Alan Gauld" <[EMAIL PROTECTED]> wrote > Tkinter has not changed hardly at all. Yuk, a double negative, sorry. That should of course say: Tkinter has hardly changed at all. Hopefully that was obvious from my subsequent comments! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A puzzle for you
John Fouhy wrote: >>From the python_dev LiveJournal community --- > >Predict the outcome of the following code: > >## >from random import * >seed() >[choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0] >## > > > random.choice( [ SyntaxError: invalid syntax, 42 the answer is young skywalker. always the answer is 42. ] ) -- "Ketchup. For the good times... " - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Magazine
I no im probally not the best pereson to go about this but maybe people in this community are. I was wondering if there was or maybe someone can start a Python maganize kinda like 3dCreative or 2d Artist. that is an PDF magazine with tutorials interviews, python news, and maybe a programming challenge or two. and free would be nice i might start this but does anyone want to help maybe? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Magazine
Amadeo Bellotti wrote: > I no im probally not the best pereson to go about this but maybe > people in this community are. I was wondering if there was or maybe > someone can start a Python maganize kinda like 3dCreative or 2d > Artist. that is an PDF magazine with tutorials interviews, python > news, and maybe a programming challenge or two. and free would be nice > i might start this but does anyone want to help maybe? > > > >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > "#1, make it so..." http://www.pyzine.com/ -- "Ketchup. For the good times... " - Ketchup Advisory Board Glenn Norton Application Developer Nebraska.gov 1-402-471-2777 [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Magazine
i saw it but it didnt quite meet what i wanted :\On 10/14/06, Glenn T Norton <[EMAIL PROTECTED]> wrote: Amadeo Bellotti wrote:> I no im probally not the best pereson to go about this but maybe > people in this community are. I was wondering if there was or maybe> someone can start a Python maganize kinda like 3dCreative or 2d> Artist. that is an PDF magazine with tutorials interviews, python > news, and maybe a programming challenge or two. and free would be nice> i might start this but does anyone want to help maybe?>> >>___>Tutor maillist - Tutor@python.org>http://mail.python.org/mailman/listinfo/tutor >>"#1, make it so..."http://www.pyzine.com/--"Ketchup. For the good times... " - Ketchup Advisory BoardGlenn NortonApplication Developer Nebraska.gov1-402-471-2777[EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Building a simple text editor
Folks, I am trying to build a simple text editor which has a couple of options of editing, displaying and saving the file. Now what I want to do is to allow teh user to keep entering the text unless he pressed ':q'. How can I add this functionality?? Thanks. REgards, Asrar -- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building a simple text editor
> I am trying to build a simple text editor which has a couple of > options of > editing, displaying and saving the file. Are you using a GUI or console? The solution is potentially quite different depending on the choice. > Now what I want to do is to allow teh user to keep entering the text > unless > he pressed ':q'. How are you reading the characters in the first place? if you can find a way to read characters from the keyboard one at a time then while True ch = getchar() if ch ==':' ch = getchar() if ch == 'q': break Will work. So the question becomers do you know how to write getchar()? Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building a simple text editor
Is it possible to make the utility like in vi, where the user keeps on entering the data and when he hits ':wq', the work is saved and the application exists. I guess the use of standard input file would be applicable??? Thanks. Regrds, Asrar On 10/14/06, Alan Gauld <[EMAIL PROTECTED]> wrote: > I am trying to build a simple text editor which has a couple of> options of> editing, displaying and saving the file. Are you using a GUI or console?The solution is potentially quite different depending on the choice.> Now what I want to do is to allow teh user to keep entering the text> unless> he pressed ':q'. How are you reading the characters in the first place?if you can find a way to read characters from the keyboardone at a time thenwhile Truech = getchar()if ch ==':' ch = getchar() if ch == 'q': breakWill work.So the question becomers do you know how to write getchar()?Alan G.___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor-- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Reading escaped characters from a file
Title: Message I have code that uses variables to hold escaped characters like "\n" or "\03". As long as the assignment is done within the code, like self.crChar = "\n", there is no problem. But When I try to read the same character string from a text file and assign it, the string is seen as just a string of characters instead of an escape sequence, and the program fails. I read the "parameter = value" pairs, like "crChar = \n", from an ASCII file and store them in a dictionary; "parameterDict[parameter] = value". Then I assign the value to the variable using "self.crChar = parameterDict["crChar"]. When I print "self.crChar", it displays "\\n" and it doesn't behave like a carriage return. Can anyone guide me toward a resolution? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading escaped characters from a file
David Heiser wrote: > > I have code that uses variables to hold escaped characters like "\n" > or "\03". As long as the assignment is done within the code, like > self.crChar = "\n", there is no problem. But When I try to read the > same character string from a text file and assign it, the string is > seen as just a string of characters instead of an escape sequence, and > the program fails. > > I read the "parameter = value" pairs, like "crChar = \n", from an > ASCII file and store them in a dictionary; "parameterDict[parameter] = > value". Then I assign the value to the variable using "self.crChar = > parameterDict["crChar"]. When I print "self.crChar", it displays "\\n > " and it doesn't behave like a carriage return. Please include the code that is causing you trouble instead of trying to sum up what you think the problem is. Quite often the problem is just a simple syntax or other error that the beginner may overlook that we can help by pointing out to you. In this situation, I believe what's happening is that you expect this: #ascii text file hello, world!\n #- end to be read into python as >>> f.readlines()[0] == 'hello, world!\n' True but no, that's not what the file says. The file says 'hello, world \\n' because you can see an actual \ in the file text, right? So in python it'll be represented by a double-backslash. The actual \n is an escape code, you can't ever see it in files. In the file #start a b c d e #end >>> print f.readlines() ['a\n','b\n','c\n','d\n','e\n'] You don't explicitly put \n in a text file to have a string with \n at the end. You hit enter at the end of the line. > > Can anyone guide me toward a resolution? > > > > ___ > 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] Reading escaped characters from a file
> I have code that uses variables to hold escaped characters like "\n" or > "\03". As long as the assignment is done within the code, like self.crChar = > "\n", there is no problem. But When I try to read the same character string > from a text file and assign it, the string is seen as just a string of > characters instead of an escape sequence, and the program fails. >: > When I print "self.crChar", it displays "\\n" and > it doesn't behave like a carriage return. david, the problem is that when you're doing it "live", Python translates the \n as a single character, NEWLINE. when you are reading those same characters from disk, what it reads is '\' followed by 'n' because that's what stored in the file and the reason why you get '\\n', which is the same as r'\n', a raw string. in "\n" the backslash is used to "escape the n," meaning to realize the special symbol \n. in "\\n", the (frontmost) backslash is used to escape the 2nd backslash, telling Python to take the backslash verbatim and to take the following 'n' as-is. in order to read in a NEWLINE, you have to just store a blank line to the disk file. off the top of my head, i can't think of a way to "eval" a '/' and 'n' to convert it into a \n... perhaps someone else here can help with that. regards, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Building a simple text editor
> I am trying to build a simple text editor which has a couple of options of > editing, displaying and saving the file. > Now what I want to do is to allow teh user to keep entering the text unless > he pressed ':q'. reading of and writing of a text file is one of the examples i added to "Core Python Programming". in fact, these are the 1st two applications that are presented to the reader to introduce them to their first pieces of Python code to study. in the application that writes text files, the user types '.' to terminate the input and save the file. that can easily be changed to 'q'. you don't need to buy the book if you don't wish... you can just get to the source code. it's available at the book's website (see below)... just go to chapter 3. (the server is down at the moment, but should be back up soon.) furthermore, in order to do what you suggest, e.g., make it work like vim where it has two modes, edit and input, you will have to build that into your application, plus have special keys to get you into that mode as well as a key (e.g., ESC) to get you out. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A puzzle for you
John Fouhy wrote: > >From the python_dev LiveJournal community --- > > Predict the outcome of the following code: > > ## > from random import * > seed() > [choice(dict((x+1,0) for x in range(1000))) for x in range(693)][0] > ## > Hmm - interesting. Given that the argument of random.choice is supposed to be a sequence (according to the docs str, unicode, list, tuple, buffer, xrange), I'd expect an exception. I also predicted the the result if no exception was raised, and that was correct. I will withhold further observation until others (who wish) may reply. -- Bob Gailer 510-978-4454 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Reading escaped characters from a file
David Heiser wrote: > > I have code that uses variables to hold escaped characters like "\n" or > "\03". As long as the assignment is done within the code, like > self.crChar = "\n", there is no problem. But When I try to read the > same character string from a text file and assign it, the string is seen > as just a string of characters instead of an escape sequence, and the > program fails. > > I read the "parameter = value" pairs, like "crChar = \n", from an ASCII > file and store them in a dictionary; "parameterDict[parameter] = value". > Then I assign the value to the variable using "self.crChar = > parameterDict["crChar"]. When I print "self.crChar", it displays "\\n > " and it doesn't behave like a carriage return. You can use the 'string_escape' codec to translate literal backslash escapes to the special characters the escapes represent: In [5]: s='this is not a newline\\n' In [6]: s.decode('string_escape') Out[6]: 'this is not a newline\n' In [7]: s Out[7]: 'this is not a newline\\n' See the difference? Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Zipfile and File manipulation questions.
Excellent suggestion! Thanks!I have a question... is endswith() case sensitive?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.
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] Building a simple text editor
"Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote > Is it possible to make the utility like in vi, where the user keeps > on > entering the data and when he hits ':wq', the work is saved and the > application exists. YES BUT THE ACTUAL CODE TO READ KEYSTROKES AS THEY ARE TYPED WILL BE VERY DIFFERENT DEPENDING ON WHEHER YOU USE A gii OR A TEXT CONSOLE. SEE MY EVENT HANDLING TOPIC FOR EXAMPLES OF BOTH STYLE TO COMPARE AND CONTRAST. Oops!! Sorry for the upper case, not meaning to shout but this mail tool has no case inversion, and its late... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld > I guess the use of standard input file would be applicable??? > > Thanks. > Regrds, > Asrar > > On 10/14/06, Alan Gauld <[EMAIL PROTECTED]> wrote: >> >> > I am trying to build a simple text editor which has a couple of >> > options of >> > editing, displaying and saving the file. >> >> Are you using a GUI or console? >> The solution is potentially quite different depending on the >> choice. >> >> > Now what I want to do is to allow teh user to keep entering the >> > text >> > unless >> > he pressed ':q'. >> >> How are you reading the characters in the first place? >> >> if you can find a way to read characters from the keyboard >> one at a time then >> >> while True >> ch = getchar() >> if ch ==':' >>ch = getchar() >>if ch == 'q': break >> >> Will work. >> >> So the question becomers do you know how to write getchar()? >> >> Alan G. >> >> >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > To HIM you shall return. > > ___ > 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.
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] executing with double click on linux
I'm afraid I don't have enough experience with Gnome to answer your questions, Alfonso. I will share what I know, though. If you could, run this: $ gnomevfs-info .pyc | grep MIME and see what it says? (If it gives you nothing back, then you need to register a MIME type for .pyc files. http://www.gnome.org/learn/admin-guide/2.14/mimetypes-modifying.html is the official Gnome documentation on how to accomplish that task) You should get a MIME type of "application/x-python-bytecode". If that checks out good, then my suggestion would be to place all of your python code in a good place (/home/user/scripts or the like) then create a desktop shortcut pointing to: "python /home/user/scripts/targetScript.pyc". If my memory serves me well, when you create a desktop shortcut you can tell it what command to run as well as what commandline arguements to pass to the program. Split it up accordingly. I've tested that out in idesk running on fluxbox, so I can't guarantee how well it will work under Gnome, but it's worth a try. Also, if your script doesn't have a GUI, you'll need to point the desktop shortcut to: "xterm -e 'python /home/user/scripts/targetScript.pyc'" (use your favorite terminal, of course...) instead of simply "python /home/user/scripts/targetScript.pyc", or you'll lose the output. (I checked against idesk/fluxbox while monitoring with Conky...my CPU shoots to 100% on a py script that I wrote that builds Markov models from the words in a given dictionary file...(yes, I was quite bored the day I wrote that...), so I know the script is indeed running even without a terminal to output to). If you create the shortcut in that fashion, you *should* be able to run whatever python bytecode you want... Hope this helps, and let me know how that works out for you... Jonathon Alfonso wrote: > Jonathon Sisson escribió: >> Alfonso wrote: >> >>> Sorry for the too obvious question. I'm new to python and have no idea >>> how can I make execute a compiled .pyc with a double click in linux, >>> with gnome. Trying to double click in a .py gives allways the question >>> wether I want to execute the text file, or read it. (This behaviour can >>> be changed with gconf-editor, but as it is for security matters, I would >>> prefer to execute the .pyc with a double click). I have tried to >>> associate python to the .pyc (first time I executed it there was no >>> programm associated), but it doesn't work. >>> >>> >> I don't know how much Linux experience you have (judging by the >> "double-click" concept, I'm assuming you're coming from a Windows >> background or are perhaps catering to users with only a Windows >> background) (correct me if I'm wrong)...so I'm going to break this down >> as much as I can. >> >> .pyc files are considered binary files by Linux. As such, bash attempts >> to execute them as binary (ELF, etc...), which obviously won't work. If >> you really need to have double-click/execute functionality, consider >> writing a small shell script to execute the .pyc file for you. >> >> For instance, let's say you have a python script "foo.py" and a compiled >> python script "foo.pyc". If you attempt to run foo.py from the shell >> and you have a proper header (i.e. #!/usr/bin/python), then bash can >> execute the script. I'm assuming that GNOME has similar functionality >> (I prefer Fluxbox to either GNOME or KDE), which allows your .py files >> to execute directly. .pyc, however, even with a file association, fails >> to launch...on my system, I get this error: >> >> $ ./foo.pyc >> bash: ./foo.pyc: cannot execute binary file >> >> bash recognizes the file as binary, but it fails to launch as an ELF >> binary (or whatever you're set up to run). To fix it, simply write a >> shell script as such: >> >> >> #!/bin/sh >> >> python /home/me/scripts/foo.pyc >> >> >> >> Name the script whatever you want (i.e. foo.sh) then run from the >> commandline: >> >> $ chmod 700 foo.sh >> >> This gives the script read/write/execute permissions for the owner of >> the script...if you require read/write/execute/etc...for group or all, >> change 700 to whatever you need. (i.e. 755 for rwxr-xr-x permissions) >> >> (Alternatively you can right click on the shell script and set >> permissions graphically...whichever you prefer) Now, you should be able >> to double-click the script (or preferably a shortcut to the script on >> your desktop), which will launch the compiled python module for you. If >> this seems like a lot of work, then perhaps you could write a shell >> script to automate the task of creating the shell script and setting >> permissions each time you create a new .pyc...doh? >> >> Hope this is a satisfactory answer...and if anyone knows something I >> have overlooked, please let Alfonso and I know. >> >> Jonathon >> >> >> >>> Thank you for your answer. >>> >>> >>> __ >>> LLama Gratis a cualquier PC del Mu
[Tutor] python equivalent of perl readlink()?
Is there a python equivalent of the perl readlink() function (e.g. one that returns the relative path in cases where a command such as ``ln -s ls /usr/local/bin/gls'' created the link? Reading the documentation on the various os.path functions, the only thing I see returns the fully resolved path rather than the relative one (/usr/local/bin/ls in the case above). Bill -- INTERNET: [EMAIL PROTECTED] Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX:(206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 ``It's time to feed the hogs'' -- Unintended Consequences ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor