[Tutor] Atomic file creation?
Dear Users, I'm looking for an atomic method for creating a file on the hard disk from python. Currently I'm using; def (command): """Creates a file with the name given by command.""" comFile = open(comFileName, 'w') comFile.close() This is not atomic as there are two operations needed to create this file. If the process was disturbed between these two files another process may not be able to read and delete the file (just reading the file name) as the above process may still hold it open. I realise I could do: import os def (command, tempDir='tempFiles', targetDir='commandDirectory'): """Creates a file with the name given by command in a temporary directory then moves it over to a target directory.""" tempName = os.path.join(tempDir,comFileName) finalName = os.path.join(targetDir,comFileName) comFile = open(tempName, 'w') comFile.close() os.rename(tempName, finalName) This is now atomic as far as anything watching targetDir is concerned. In other words as soon as it can be seen in the directory it is safe to be read and destroyed with out having to worry about another process not having closed the file for what ever reason. I do have two problems with this though; 1. This may fail under windows if another file already exists with this file name in the target directory. I always try to get my code working on Linux and windows, this leaves my code more robust and interestingly sometimes the Linux interpreter picks up different errors than the windows interpreter and visa versa. 2. It doesn't look very nice! I'm assuming there must be something in python to create a and release a file on the system in one line of code? Thank in advance of any help. Cheers, Wesley Brooks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] for vs while
All, I have a dumb question...hopefully someone can shed some light on the difference between for and while in the situation below. I'm trying to iterate through a list I've created. The list consists of a command, followed by a 'logging' message (a message printed to a console or log file after the command is run). Here's a small snippet of code: # a list which includes (1) a command, and (2) something to be dumped into a log file after the command runs stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] #works i = 0 ; j = 1 while i < len( stuff ): os.system( str( stuff[ i ] ) ) print stuff[ j ] i += 1 ; j += 1 The while loop does precisely what it should do: it runs the first command using os.system(), and then prints out the string in the second position of the list. Then I tried to do the same thing with a for loop that looks logically equivalent. I replaced the while loop with this for loop: # doesn't work for i in len( stuff ): os.system( stuff[ i ] ) j = i + 1 print stuff[ j ] Python doesn't like it, though. It gives me the following error: Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable What precisely causes this error? I come from a C background, and while and for loops can be molded to do precisely the same thing; it doesn't seem like this is the case in this scenario. Thoughts/ideas appreciated. :) Thanks! .james ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Replacing "source" in Bash Scripting
James wrote: > Hi. > > I'm re-writing a rather complex bash script I've been using for years > in Python. The bash script uses a relatively simple configuration > file in order to get pertinent information before it runs. The > configuration file is relatively simple: about 30 variables are > defined in this manner in the config file: > > VARNAME=value > > In the bash script I simply "source" this configuration file and the > script runs merrily using those variables defined in the > configuration file. i.e., > > "source configFile" > > I'm trying to implement similar behavior in a Python script, > specifically having a configuration file (with a list of variables > and their values defined) that my Python program will read once > running. I'm not really sure what the best way to implement this is. > > Ideas? > The simplest, IMHO, is: create and import a module (e.g. config.py) with a series of assignments: VARNAME1='value1' VARNAME2='value2' In the script: from config import * There are also a number of modules in the Python library for doing more complex config file manipulation. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] case insensitivity
Christopher Spears wrote: > I wrote a script that checks if two strings match. > The script ignores case. > > #!/usr/bin/env python > > string_a = raw_input("Enter a string: ") > string_b = raw_input("Enter another string: ") > > if cmp(string_a.lower(), string_b.lower()) == 0: > Simpler: if string_a.lower() == string_b.lower(): > print "The strings match!" > else: > print "The strings don't match!" > > Is this the best way to implement case insensitivity? Or if you are seeking ultimate terseness: print "The strings " + ("don't", "")[string_a.lower() == string_b.lower()] + " match!" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to Python and Linux
* Armand Nell (Wed, 26 Sep 2007 08:07:12 +0200) > I am new to python programming and also the linux enviroment most of my > skills are windows based and programming skills is visual basics. I decided > that it would be a great start and new direction for me to learn python and > at the same time linux. However I have already run into a wall, and any help > would be appreciated even if you can direct me where to find the info or > 'turor'. > [...] > In windows, if i write a program in Python and save it I then can simply > double click the icon and the program will execute in a console window. Now > under Fedoracore I write my program in gedit save it in my > \home\(username)\python directory, when I double click it, it opens up agian > in gedit. Now true it is maybe a simple error from me but mostly it is me > that don't know how to work with python on linux. > > I would like to know how do I test(run) the programs I write under > fedoracore? It's exactly the same as with with Visual Basic ("visual basics? Are you sure you have experience in that language?") and Windows: run it in a command window (like "python myscript.py") or associate the file type (.py) with the program. How you do that depends on your desktop environment (KDE or Gnome probably) but it shouldn't take you more than ten seconds to find out how to do it. Thorsten ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] for vs while
James wrote: > Great! I was under the impression that the range was implied, but I > guess not. ;) No. One of the core Python values is "Explicit is better than implicit." If you like implicit behaviour, try Perl ;-) Type 'import this' at the Python prompt for more... Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Replacing "source" in Bash Scripting
James wrote: > Hi. > > I'm re-writing a rather complex bash script I've been using for years > in Python. The bash script uses a relatively simple configuration > file in order to get pertinent information before it runs. The > configuration file is relatively simple: about 30 variables are > defined in this manner in the config file: > > VARNAME=value > > In the bash script I simply "source" this configuration file and the > script runs merrily using those variables defined in the > configuration file. i.e., > > "source configFile" > > I'm trying to implement similar behavior in a Python script, > specifically having a configuration file (with a list of variables > and their values defined) that my Python program will read once > running. I'm not really sure what the best way to implement this is. Write configFile as a Python source file, then import configFile print configFile.VARNAME or whatever you want to do with VARNAME If configFile.VARNAME is too wordy for you you can import configFile as cf print cf.VARNAME or from configFile import VARNAME print VARNAME or (*not* recommended, it obscures your code and risks importing more than you want) from configFile import * print VARNAME You can also use .ini file format and the ConfigParser module if you prefer. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] for vs while
On 9/28/07, James <[EMAIL PROTECTED]> wrote: > > > # doesn't work > for i in len( stuff ): > os.system( stuff[ i ] ) > j = i + 1 > print stuff[ j ] > > > Traceback (most recent call last): >File "", line 1, in > TypeError: 'int' object is not iterable > > What precisely causes this error? I come from a C background, and > while and for loops can be molded to do precisely the same thing; it > doesn't seem like this is the case in this scenario. You don't want to iterate through the length of the object (stuff), you want to iterate through the object itself. for i, j in stuff: os.system(i) print j and stuff would look like: stuff = [("cat /etc/passwd", "viewed /etc/passwd")] insert the pairs in tuples, rather than a list. cheers Josh ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Atomic file creation?
"1. This may fail under windows if another file already exists with this file name in the target directory. I always try to get my code working on Linux and windows, this leaves my code more robust and interestingly sometimes the Linux interpreter picks up different errors than the windows interpreter and visa versa." I'd check to see if the destination file exists before doing all of the above. I think your method is fine. Atomic file creation is not a common worry. I think this is a wholly reasonable quantity of code to pull it off. --Michael On 9/28/07, Wesley Brooks <[EMAIL PROTECTED]> wrote: > Dear Users, > > I'm looking for an atomic method for creating a file on the hard disk > from python. > > Currently I'm using; > > def (command): > """Creates a file with the name given by command.""" > comFile = open(comFileName, 'w') > comFile.close() > > This is not atomic as there are two operations needed to create this > file. If the process was disturbed between these two files another > process may not be able to read and delete the file (just reading the > file name) as the above process may still hold it open. > > I realise I could do: > > import os > > def (command, tempDir='tempFiles', targetDir='commandDirectory'): > """Creates a file with the name given by command in a temporary > directory then moves it over to a target directory.""" > tempName = os.path.join(tempDir,comFileName) > finalName = os.path.join(targetDir,comFileName) > comFile = open(tempName, 'w') > comFile.close() > os.rename(tempName, finalName) > > This is now atomic as far as anything watching targetDir is concerned. > In other words as soon as it can be seen in the directory it is safe > to be read and destroyed with out having to worry about another > process not having closed the file for what ever reason. > > I do have two problems with this though; > > 1. This may fail under windows if another file already exists with > this file name in the target directory. I always try to get my code > working on Linux and windows, this leaves my code more robust and > interestingly sometimes the Linux interpreter picks up different > errors than the windows interpreter and visa versa. > > 2. It doesn't look very nice! I'm assuming there must be something in > python to create a and release a file on the system in one line of > code? > > Thank in advance of any help. > > Cheers, > > Wesley Brooks. > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] for vs while
I shiver at the thought of Perl. ;) Thanks to everyone for your quick and helpful responses! .james On Sep 28, 2007, at 11:25 AM, Kent Johnson wrote: > James wrote: >> Great! I was under the impression that the range was implied, but >> I guess not. ;) > > No. One of the core Python values is "Explicit is better than > implicit." If you like implicit behaviour, try Perl ;-) > > Type 'import this' at the Python prompt for more... > > Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] for vs while
James wrote: > All, > > I have a dumb question...hopefully someone can shed some light on the > difference between for and while in the situation below. > > I'm trying to iterate through a list I've created. The list consists > of a command, followed by a 'logging' message (a message printed to a > console or log file after the command is run). > > Here's a small snippet of code: > > # a list which includes (1) a command, and (2) something to be > dumped into a log file after the command runs > stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] > > #works > i = 0 ; j = 1 > while i < len( stuff ): > os.system( str( stuff[ i ] ) ) > print stuff[ j ] > i += 1 ; j += 1 > > The while loop does precisely what it should do: it runs the first > command using os.system(), and then prints out the string in the > second position of the list. Are you sure? When I run this I get sh: line 1: [cat /etc/password]: No such file or directory ['viewed /etc/password'] sh: line 1: [viewed /etc/password]: No such file or directory and then an IndexError. It is calling os.system() on the string representation of a list, and it should increment i and j by 2 each time through the loop. Here is a version that works for me: stuff = [ "cat /etc/password" , "viewed /etc/password" ] #works i = 0 while i < len( stuff ): os.system( str( stuff[ i ] ) ) print stuff[ i+1 ] i += 2 > Then I tried to do the same thing with a for loop that looks > logically equivalent. I replaced the while loop with this for loop: > > # doesn't work > for i in len( stuff ): > os.system( stuff[ i ] ) > j = i + 1 > print stuff[ j ] > > Python doesn't like it, though. It gives me the following error: > > Traceback (most recent call last): >File "", line 1, in > TypeError: 'int' object is not iterable > > What precisely causes this error? I come from a C background, and > while and for loops can be molded to do precisely the same thing; it > doesn't seem like this is the case in this scenario. Right. Python for loops are not like anything in C. They iterate over the values of a sequence. The thing after 'in' has to be an instance of a sequence such as a list or tuple, not an integer. (Technically it has to be an instance of an iterable but I don't want to confuse the issue.) The way I would write this program would be to make 'stuff' a list of pairs, where each pair contains a command and the value to print: # Note the parentheses which define a tuple stuff = [ ("cat /etc/password" , "viewed /etc/password") ] # The for statement assigns the elements of each tuple to cmd and echo for cmd, echo in stuff: os.system(cmd) print echo It's worth your time learning about Python data structures and for loops. They are very powerful and useful and unlike anything built-in to C. With a background in C you should find the official tutorial pretty easy to read: http://docs.python.org/tut/tut.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] for vs while
On Sep 28, 2007, at 10:59 AM, bob gailer wrote: > James wrote: >> All, >> >> I have a dumb question...hopefully someone can shed some light on >> the difference between for and while in the situation below. >> >> I'm trying to iterate through a list I've created. The list >> consists of a command, followed by a 'logging' message (a message >> printed to a console or log file after the command is run). >> >> Here's a small snippet of code: >> >> # a list which includes (1) a command, and (2) something to be >> dumped into a log file after the command runs >> stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] >> >> #works >> i = 0 ; j = 1 >> while i < len( stuff ): >> os.system( str( stuff[ i ] ) ) >> print stuff[ j ] >> i += 1 ; j += 1 >> >> The while loop does precisely what it should do: it runs the >> first command using os.system(), and then prints out the string >> in the second position of the list. >> >> Then I tried to do the same thing with a for loop that looks >> logically equivalent. I replaced the while loop with this for loop: >> >> # doesn't work >> for i in len( stuff ): >> > Try this: >> for i in range(len(stuff)): >> >> >> os.system( stuff[ i ] ) >> j = i + 1 >> print stuff[ j ] >> >> Python doesn't like it, though. It gives me the following error: >> >> Traceback (most recent call last): >>File "", line 1, in >> TypeError: 'int' object is not iterable >> >> What precisely causes this error? I come from a C background, >> and while and for loops can be molded to do precisely the same >> thing; it doesn't seem like this is the case in this scenario. >> >> Thoughts/ideas appreciated. :) >> > for expects, as the error says, an "iterable". range() provides an > iterable. len() just gives an integer. Great! I was under the impression that the range was implied, but I guess not. ;) > BTW I find it very hard to read code where there are spaces next to > () and []. I find it difficult to read code where there *aren't* spaces next to the () and [] and there are several parenthesis/brackets next to each other. :) Personal preference. Thanks again. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] for vs while
James wrote: > All, > > I have a dumb question...hopefully someone can shed some light on the > difference between for and while in the situation below. > > I'm trying to iterate through a list I've created. The list consists > of a command, followed by a 'logging' message (a message printed to a > console or log file after the command is run). > > Here's a small snippet of code: > > # a list which includes (1) a command, and (2) something to be > dumped into a log file after the command runs > stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] > > #works > i = 0 ; j = 1 > while i < len( stuff ): > os.system( str( stuff[ i ] ) ) > print stuff[ j ] > i += 1 ; j += 1 > > The while loop does precisely what it should do: it runs the first > command using os.system(), and then prints out the string in the > second position of the list. > > Then I tried to do the same thing with a for loop that looks > logically equivalent. I replaced the while loop with this for loop: > > # doesn't work > for i in len( stuff ): > Try this: > for i in range(len(stuff)): > > > > os.system( stuff[ i ] ) > j = i + 1 > print stuff[ j ] > > Python doesn't like it, though. It gives me the following error: > > Traceback (most recent call last): >File "", line 1, in > TypeError: 'int' object is not iterable > > What precisely causes this error? I come from a C background, and > while and for loops can be molded to do precisely the same thing; it > doesn't seem like this is the case in this scenario. > > Thoughts/ideas appreciated. :) > for expects, as the error says, an "iterable". range() provides an iterable. len() just gives an integer. BTW I find it very hard to read code where there are spaces next to () and []. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] for vs while
On 9/28/07, James <[EMAIL PROTECTED]> wrote: > > All, > > I have a dumb question...hopefully someone can shed some light on the > difference between for and while in the situation below. > > I'm trying to iterate through a list I've created. The list consists > of a command, followed by a 'logging' message (a message printed to a > console or log file after the command is run). > > Here's a small snippet of code: > ># a list which includes (1) a command, and (2) something to be > dumped into a log file after the command runs >stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] > >#works >i = 0 ; j = 1 >while i < len( stuff ): >os.system( str( stuff[ i ] ) ) >print stuff[ j ] >i += 1 ; j += 1 Here you're basing yourself off of the index of the item in the list, so stuff[0], stuff[1], etc. The while loop does precisely what it should do: it runs the first > command using os.system(), and then prints out the string in the > second position of the list. > > Then I tried to do the same thing with a for loop that looks > logically equivalent. I replaced the while loop with this for loop: > ># doesn't work >for i in len( stuff ): >os.system( stuff[ i ] ) >j = i + 1 >print stuff[ j ] Here, you're using *for* in a non-Pythonic way. You mean to use i as an iterator, but len( stuff ) is a simple integer. You could do it this way: for i in range( len(stuff)): os.system( stuff[i] ) j = i + 1 print stuff[ j ] turning the single integer into a range of integers that you can iterate over. Tony R. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to Python and Linux
* Thorsten Kampe (Fri, 28 Sep 2007 14:09:24 +0100) > It's exactly the same as with with Visual Basic [...] Guess I mixed that up with VBScript... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] for vs while
On 9/28/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > > > It's worth your time learning about Python data structures and for > loops. They are very powerful and useful and unlike anything built-in to > C. With a background in C you should find the official tutorial pretty > easy to read: > http://docs.python.org/tut/tut.html I found Dive Into Python (http://www.diveintopython.org) helpful as well coming from a primarily C background. cheers Josh ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Replacing "source" in Bash Scripting
Hi. I'm re-writing a rather complex bash script I've been using for years in Python. The bash script uses a relatively simple configuration file in order to get pertinent information before it runs. The configuration file is relatively simple: about 30 variables are defined in this manner in the config file: VARNAME=value In the bash script I simply "source" this configuration file and the script runs merrily using those variables defined in the configuration file. i.e., "source configFile" I'm trying to implement similar behavior in a Python script, specifically having a configuration file (with a list of variables and their values defined) that my Python program will read once running. I'm not really sure what the best way to implement this is. Ideas? Thanks! .james ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [tutor]Help needed to read Ascii file in wxPython
Varsha Purohit wrote: > I am writing a program basically in python gui to open a file and > display its content. i know similar program in simple > python but wanna figure out how to do that in wxpython... See DocViewDemo.py in the wxPythohn demo package /Samples/samples/docview/DocViewDemo.py Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to adjust a text file...
GTXY20 wrote: > Hi There, > > For some reason I am getting no results and if I alter the code to relect: > > > inp = open('input.txt') > > for line in inp: > fields = line.split(",") > ProdId = fields[0] > products = fields[1:] > for product in products: > print('%s\t%s\n' % (ProdId, Product)) Names are case-sensitive in Python; product and Product are not the same. > > I am left with an error indicating that product is not defined In the future when you get an error, please copy and paste the entire error message, including the traceback, into your email. Also, please use Reply All to reply to the list. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] for vs while
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 Try: for item in stuff: os.system(item[0]) print item[1] Alternativly: for cmd, msg in stuff: os.system(cmd) print msg Andreas James wrote: > All, > > I have a dumb question...hopefully someone can shed some light on the > difference between for and while in the situation below. > > I'm trying to iterate through a list I've created. The list consists > of a command, followed by a 'logging' message (a message printed to a > console or log file after the command is run). > > Here's a small snippet of code: > > # a list which includes (1) a command, and (2) something to be > dumped into a log file after the command runs > stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] > > #works > i = 0 ; j = 1 > while i < len( stuff ): > os.system( str( stuff[ i ] ) ) > print stuff[ j ] > i += 1 ; j += 1 > > The while loop does precisely what it should do: it runs the first > command using os.system(), and then prints out the string in the > second position of the list. > > Then I tried to do the same thing with a for loop that looks > logically equivalent. I replaced the while loop with this for loop: > > # doesn't work > for i in len( stuff ): > os.system( stuff[ i ] ) > j = i + 1 > print stuff[ j ] > > Python doesn't like it, though. It gives me the following error: > > Traceback (most recent call last): >File "", line 1, in > TypeError: 'int' object is not iterable > > What precisely causes this error? I come from a C background, and > while and for loops can be molded to do precisely the same thing; it > doesn't seem like this is the case in this scenario. > > Thoughts/ideas appreciated. :) > > Thanks! > .james > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFG/SVFHJdudm4KnO0RAhvcAKCKaySj7gnZEJv1Gbhy4ePmynW36wCg6lK5 CTCcgUE8AY83tVmRS+8VDDI= =aPMB -END PGP SIGNATURE- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] case insensitivity
Christopher Spears wrote: > I wrote a script that checks if two strings match. > The script ignores case. > > #!/usr/bin/env python > > string_a = raw_input("Enter a string: ") > string_b = raw_input("Enter another string: ") > > if cmp(string_a.lower(), string_b.lower()) == 0: if string_a.lower() == string_b.lower(): > Is this the best way to implement case insensitivity? As far as I know. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to convert array into tuple
bhaaluu wrote: > Can you explain how this works? How would this be written in > a "conventional" way? I'm not sure if this is addressed to me but I'll reply anyway. :) foo = [1,2,3,4,5,6] [(foo[i],foo[i+1]) for i in range(0,len(foo),2)] range(0,len(foo)) would create a list of consecutive numbers starting from the first argument (0) till (but not including) the last (len(foo)) This will run as range(0,6) and will return [0,1,2,3,4,5] The 2 as the third argument to range specifies the increment (common difference of the arithmetic progression). So if you say range(0,10,2), you'd get [0,2,4,6,8]. If you say range(0,10,3), you'd get [0,3,6,9] etc. Thus the list comprehension is written to iterate over [0,2,4] i is used as the loop variable in the list comprehension and we return tuples consisting of the ith and the i+1th elements of the list. So, it should return [(foo[0],foo[1]), (foo[2],foo[3]), (foo[4],foo[5]) ] Which is the result. Using a for loop, you can write this as res = [] for i in range(0,len(foo),2): res.append( (foo[i],foo[i+1],)) print res I hope I'm clear > Also, what kinds of ways might this be used? I can't off the cuff think of anything. Peace -- ~noufal ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] VOID Can a python program access the python interpreter?
Never mind. Sorry, I should have thought about this more before sending this. In a way I already have access to the interpreter. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Can a python program access the python interpreter?
Let's say I have a program that is learning how to find patterns in a list etc. list = [1,2,3,5,8,13] So the python program (Kitty.py) opens the python interpreter and copies this list to it. It then can try some pattern finding things it already has stored (PositionN+1 - PositionN etc.) That would be nice. As it stands I have to program all these rules (like Kitty.py typing nonsensical commands, or going outside the array) when the interpreter already has all these rules. I can just insert Kitty.py's "junk" into try exception handling... I don't know how to make this easier. Maybe I just need to get the program out of the computer so that it can use the interpreter. Hey, maybe that portable python... Hmmm Any other ideas (I only have Internet at work, and I.T. would hack up a hair ball if I tried to do this here). James Carnell ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to adjust a text file...
Thanks... I was able to use the following to get what i needed done: inp = open('input.txt', 'r') out = open('output.txt', 'w') for line in inp: Fields = line.split(",") ID = Fields[0] ProductMess = Fields[1] Product = ProductMess.split() for item in Funds: out.write ('%s\t%s\n'%(ID, Product)) Now my next challenge is to link a current table to this file and replace values in the Product area based on the value - sort of like a Global replace. Any hints as to where Python might have some sort of lookup table functionality. M. On 9/27/07, Kent Johnson <[EMAIL PROTECTED]> wrote: > > GTXY20 wrote: > > Hi, > > > > I have a CSV file as follows: > > > > IDProducts > > 1 a b c d > > 1 a e > > 2 a b c > > 2 a > > 3 b c > > 3 a > > 4 d > > 5 a d > > > > I am trying to write a script that will take the CSV file and output > > another text file as follows: > > > > ID Products > > 1a > > 1b > > 1c > > 1d > > 1a > > 1e > > > > etc.. for all of the ID's essentially I need to create a single instance > > for products for each ID - currently the products are separated by a > > space. I am thinking I need a for loop that will search on the space as > > a delimiter... > > I should probably be teaching you to fish but tonight I have extra fish > :-) > > If the products are single words then this is very simple. Something like > > inp = open('input.txt') > out = open('output.txt') > > # Headers > inp.next() > out.write('ID\tProducts\n') > > for line in inp: > fields = line.split() > prodId = fields[0] > products = fields[1:] > for product in products: > out.write('%s\t%s\n' % (prodId, product)) > > inp.close() > out.close() > > > If the product text is more complex then you might want to use the csv > module to help read and write the file. > > BTW in Python 3 you can write > prodId, *products = fields.split() > > http://www.python.org/dev/peps/pep-3132/ > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to adjust a text file...
GTXY20 wrote: > Now my next challenge is to link a current table to this file and > replace values in the Product area based on the value - sort of like a > Global replace. Any hints as to where Python might have some sort of > lookup table functionality. A dict is a lookup table (a hash table, specifically). http://docs.python.org/tut/node7.html#SECTION00750 http://docs.python.org/lib/typesmapping.html Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] detecing palindromic strings
I'm trying to write a script that detects if a string is palindromic (same backward as it is forward). This is what I have so far: #!/usr/bin/env python my_str = raw_input("Enter a string: ") string_list = [] for s in my_str: string_list.append(s) string_list_orig = string_list string_list.reverse() print string_list_orig print string_list The problem is that the script gives results like so: [EMAIL PROTECTED] ./chap6 117> python palindromic.py Enter a string: abc ['c', 'b', 'a'] ['c', 'b', 'a'] Now I understand pointers and Python! :-) Since string_list_orig is pointing to string_list, when I reversed string_list, string_list_orig was reversed as well. How do I get around this? Is there a better way to write this script? I can't figure out how to loop through a string starting from the last character. "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "I generally know what I'm doing." -Buster Keaton ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] detecing palindromic strings
Christopher Spears wrote: > I'm trying to write a script that detects if a string > is palindromic (same backward as it is forward). This > is what I have so far: > > #!/usr/bin/env python > > my_str = raw_input("Enter a string: ") > > string_list = [] > > for s in my_str: > string_list.append(s) > > string_list_orig = string_list > > string_list.reverse() > > print string_list_orig > print string_list > > The problem is that the script gives results like so: > [EMAIL PROTECTED] ./chap6 117> python palindromic.py > Enter a string: abc > ['c', 'b', 'a'] > Well, since you've converted the string to a list, what you would like to do is: print "".join( string_list_orig ) to connect them back together. However, you can simplify the code greatly: >>> s = "abcd" >>> print s[::-1] dcba >>> if s == s[::-1]: ... print "yay" ... >>> s = "abcdcba" >>> if s == s[::-1]: ... print "yay" ... yay > ['c', 'b', 'a'] > > Now I understand pointers and Python! :-) Since > string_list_orig is pointing to string_list, when I > reversed string_list, string_list_orig was reversed as > well. > > How do I get around this? Is there a better way to > write this script? I can't figure out how to loop > through a string starting from the last character. > > > "I'm the last person to pretend that I'm a radio. I'd rather go out and be a > color television set." > -David Bowie > > "Who dares wins" > -British military motto > > "I generally know what I'm doing." > -Buster Keaton > ___ > 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] detecing palindromic strings
On Fri, 28 Sep 2007, Christopher Spears wrote: > I'm trying to write a script that detects if a string > is palindromic (same backward as it is forward). This > is what I have so far: > my_str = raw_input("Enter a string: ") > string_list = [] Here you are creating a list and assiging the name string_list to it. > for s in my_str: > string_list.append(s) Now you've manipulated this list > string_list_orig = string_list Here is the problem: you're thinking you're creating another list, named string_list_orig, which is a copy of string_list. you're not. What you're actually doing is assigning another name, string_list_orig, to the existing list that was created above. > string_list.reverse() Now you're reversing that single list. > print string_list_orig > print string_list Now you're printing that list twice, once using each name. > > The problem is that the script gives results like so: > [EMAIL PROTECTED] ./chap6 117> python palindromic.py > Enter a string: abc > ['c', 'b', 'a'] > ['c', 'b', 'a'] Using your approach, the easiest quick fix is to replace the line: string_list_orig = string_list with: string_list_orig = string_list[:] This creates a new list by slicing from string_list, and assigns it a name string_list_orig. Then you're dealing with two different lists, and reversing one does not affect the other. The notation string_list[:] produces a slice of a list. You usually see it with numbers in there, a la: >>> L = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] >>> L[2:5] ['C', 'D', 'E'] This slices from position 2 up to (but not including) position 5. ('A' is at position 0). The default for where to start is 0, so L[:5] is the same as L[0:5] : >>> L[:5] ['A', 'B', 'C', 'D', 'E'] The default for where to end is the end of the list, so L[2:] is the same as L starting at 2 and going to the end of the list: >>> L[2:] ['C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] Putting those two defaults together, leaving both the start and end out means to start at the first element and go all the way to the end: >>> L[:] ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] So that's what the funky [:] notation gets you. > How do I get around this? Is there a better way to > write this script? I can't figure out how to loop > through a string starting from the last character. You can slice strings the same way you can slice lists. And what's more, you can specify a third parameter on the slice that specifies the stepping of the slicing; the default is 1, but, for example, using 2 will select every other element: >>> S = "ABCDEFGHIJ" >>> S[::2] 'ACEGI' And, here's the thing: if you use a negative number for ttep, it works from the right side of the string, rather than the left. So, if you use a step of -1 you get: >>> S[::-1] 'JIHGFEDCBA' And that's the easiest way to reverse a string, rather than converting it to a list and reversing the list. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] detecing palindromic strings
Greetings, Try something with this: >>> string = 'abc' >>> string 'abc' >>> for i in range(len(string)-1,-1,-1): ... print string[i], ... c b a -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html On 9/28/07, Christopher Spears <[EMAIL PROTECTED]> wrote: > I'm trying to write a script that detects if a string > is palindromic (same backward as it is forward). This > is what I have so far: > > #!/usr/bin/env python > > my_str = raw_input("Enter a string: ") > > string_list = [] > > for s in my_str: > string_list.append(s) > > string_list_orig = string_list > > string_list.reverse() > > print string_list_orig > print string_list > > The problem is that the script gives results like so: > [EMAIL PROTECTED] ./chap6 117> python palindromic.py > Enter a string: abc > ['c', 'b', 'a'] > ['c', 'b', 'a'] > > Now I understand pointers and Python! :-) Since > string_list_orig is pointing to string_list, when I > reversed string_list, string_list_orig was reversed as > well. > > How do I get around this? Is there a better way to > write this script? I can't figure out how to loop > through a string starting from the last character. > > > "I'm the last person to pretend that I'm a radio. I'd rather go out and be a > color television set." > -David Bowie > > "Who dares wins" > -British military motto > > "I generally know what I'm doing." > -Buster Keaton > ___ > 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] detecing palindromic strings
On Fri, Sep 28, 2007 at 04:59:26PM -0700, Christopher Spears wrote: > How do I get around this? Is there a better way to > write this script? I can't figure out how to loop > through a string starting from the last character. A string is a sequence of chars, and you can use slices with it [1]. In [23]: a = 'abcdef' In [24]: a[::-1] Out[24]: 'fedcba' Tiago. [1] - http://docs.python.org/lib/typesseq.html ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] creating the equivalent of string.strip()
I'm working out of chapter 6 of Core Python Programming (2nd Edition). For one problem, I am supposed to write a script that is the equivalent of string.strip(). Obviously, using any version of string.strip() defeats the purpose of the exercise. I'm not sure how to proceed. My biggest stumbling block is how to detect the leading and trailing whitespace. If I wanted to remove all whitespace in a string, I would probably break the string into its individual components, cycle through the string, detect the whitespace, and remove them. Any hints? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor