Re: [Tutor] reading file, adding to each line, writing file
> Hello everybody, > > I have easily spent some four hours on this problem, and I am now asking > for rescue. > > Here is what I am trying to do: I have a file ("step2", with some 30 or > so lines. To each line I would like to add " -d" at the end. Finally, I > want to save the file under another name ("pyout". > So far I have managed to read the file, line by line, and save it under > another name: > > > > # add " -d" to each line of a textfile > > infile = open("step2", 'r') # open file for appending > outfile = open("pyout","a") # open file for appending > > line = infile.readline()# Invokes readline() method on file > while line: > outfile.write(line),# trailing ',' omits newline character > line = infile.readline() > > infile.close() > outfile.close() > > > > As I said, before writing to file "pyout" I would like to append the > string " -d" to each line. But how, where? I can't append to strings > (which the lines gained with infile.readline() seem be), and my trial > and error approach has brought me nothing but a headache. > > Thanks for your help! > > David > Hi David! My solution of your problem would be the following: >>> infile = open('step2', 'r') >>> str = infile.read() >>> infile.close() >>> outfile = open('pyout', 'a') >>> outfile.write(str.replace('\n', ' -d\n')) >>> outfile.close() hope helped cheers! Tiefeng Wu ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] tkinter and visual with objects
I'm trying to make this very simple program, where the idea is that you click a tkinter button named "Ball" and then a ball will appear in the visual window. Problem is that the window itself doesn't pop up until the button is pressed and the ball is created. I would like it to start out blank, and then have the ball appear in it when the button is pressed. I thought that having "self.display=display()" in the __init__ of the Application would do this, but it doesn't seem to. What do I need to add to this code to make it start out with a blank window? from visual import * from Tkinter import * import sys class Ball: def __init__(self): sphere(pos=(0,0,0)) class Application: def __init__(self, root): self.frame = Frame(root) self.frame.pack() self.display=display() self.button=Button(self.frame, text="Ball", command=self.ball) self.button.pack() def ball(self): self.ball=Ball() root=Tk() app=Application(root) root.mainloop() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sort of database & "family tree" question
"Timo" wrote class Person: def __init__(self, parser): self.first = parser.get(person, 'firstName') Hey Alan, thanks for that explanation! But the class you gave, does almost the same thing as my function. That was my point. Its just a prettier way of handling it and slightly easier to use sionce you don;t need to quote the field names, just use the dot notation. both store the info in a dic, so to retrieve info for a certain person, we both have to do the same thing. Or am I missing something here? The class is less typing. Youcreate a dictionary of dictionaries, I create a dictionary of objects - which are easier to access. However the class can also have methods added to do searches, follow the tree etc. You could also add the people dictionary as a class variable which would add to the conceptual consistency of the solution.. But you are right, classes are pretty much fancy dictionaries and you could write the "methods" as standalone functions operating on the dictionaries. Either way the biggest issue I see is the lack of a unique key for your dictionary. Using names as a key is a bad idea especially in familiies where the same names tend to get used over and over. You really should consider adding a unique ID field and use that to populate the father/mother fields. decision. Normally I would agree with you and use: class Person: def __init__(self, first, last, father, mother): self.first = first self.last = last self.father = father self.mother = mother I would definitely use this one and then you can instantiate it with: p = Person(parser.get(person,'ID', parser.get(person,'firstname', parser.get(person,'lastname', parser.get(person,'father', parser.get(person,'mother',) people[p.ID] = p print people[id].first If I do it like this, I will have to parse all the data from the file and then send them to this class and then call this class again to retrieve it. You can store it in the class as you parse the file just as you did with your dictionary. You don't call the class again you use the people dictionary: A big bit of the advantage of OOP is not that it allows you to do stuff you couldn't do without it (although occasionaly this is true) but rather that it makes the code look cleaner, more readable. Then I like my function better. But again, I would love to hear if I'm wrong. Its not a metter of "wrong" its a matter of style. Using classes usually produces more readable code, with less typing. You can also add methods to prettty print a person (by implementing the __str__ method), search the people dictionary for a person (by implementing comparison methods) You then wind up writing code that looks like this: # imagine you have a person object p1... for p in people: if p1.ID == p.father: print "The father is', p Using dictionaries you get someting like: for p in people: if p1['ID'] == p['father']: print "The father is", p['first'], p['last'] Or if you write a print function: for p in people: if p1['ID'] == p['father']: print "The father is", printPerson(p) I think the first version is easier to read. But it is admittedly doing the same thing. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading binary files
eShopping wrote: The file is around 800 Mb but I can't get hold of it until next week so suggest starting a new topic once I have a cut-down copy. OK will wait with bated breath. Well, did you read on? What reactions do you have? I did (finally) read on and I am still a little confused, though less than before. I guess the word UNFORMATTED means that the file has no format Depends on what you mean by format. When you use % formatting in Python it is the same thing as a FORMATTED WRITE in FORTRAN - a set of directives that direct the translation of data to human readable text. Files per se are a sequence of bytes. As such they have no "format". When we examine a file we attempt to make sense of the bytes. Some of the bytes may represent ASCII printable characters - other not.The body of this email is a sequence of ASCII printable characters that make sense to you when you read them. The file written UNFORMATTED has some ASCII printable characters that you can read (e.g. DISTANCE), some that you can recognize as letters, numbers, etc but are not English words, and non-printable characters that show up as "garbage" symbols or not at all. Those that are not "readable" are the internal representation of numbers. though it presumably has some structure? One major hurdle is that I am not really sure about the difference between a Python binary file and a FORTRAN UNFORMATTED file so any pointers would be gratefully received There is no such thing as a "Python binary file". When you open a file with mode 'b' you are asking the file system to ignore line-ends. If you do not specify 'b' then the file system "translates" line-ends into \n when reading and translates \n back to line-ends. The reason for this is that different OS file systems use different codes for line-ends. By translating them to and from \n the Python program becomes OS independent. Windows uses ctrl-M ctrl-J (carriage return - line feed; \x0d\x0a). Linux/Unix uses ctrl-J (line feed; \x0a). Mac uses ctrl-M (carriage return; \x0d). Python uniformly translates these to \n (x0a) When processing files written without line-ends (e.g. UNFORMATTED) there may be line-end characters or sequences that must NOT be treated as line-ends. Hence mode 'b' Example: >>> x=open('x','w') # write "normal" allowing \n to be translated to the OS line end. >>> x.write("Hello\n") >>> x=open('x','rb') # read binary, avoiding translation. >>> x.read() 'Hello\r\n' where \r = \x0d -- Bob Gailer Chapel Hill NC 919-636-4239 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading file, adding to each line, writing file
"David" wrote Here is my latest try, which works: # add " -d" to each line of a textfile infile = open("step3", 'r') outfile = open("pyout","a") line = infile.readline()# Invokes readline() method on file line is now a string representing a line in the file. for i in line: You are now iterating over every character in line line2 = line[:-1] + " -d\n" So you repeat this assignment for every character. No harm done its the same every time. Just very inefficient! outfile.write(line2), # trailing ',' omits newline character But you are writing the same line for every character - did you find lots of duplicate lines in the output? line = infile.readline() And now you reset line to the next line so invalidating some of what I njust said. I doubt this actually works properly although it may appear to! The use of the for loop is much simpler, avoiding all the readline confusion: infile = open("step3", 'r') outfile = open("pyout","a") for line in infile: # no need for readline outfile.write(line.rstrip() + " -d\n") infile.close() outfile.close() print "done!" That's all you need! for loops reading direct from the file are ideally suited to this kind of program and indeed any situation where you are handling a fixed size input. while loops are better for when you don't know where the end will be or even if there will be an end! HTH, Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading binary files
"eShopping" wrote I now understand why Python gave me the results it did ... it looks like reading the FORTRAN file will be a non-trivial task so probably best to wait until I can post a copy of it. You don't say which OS you are on but you can read the binary file into a hex editor and see the structure. If you are on *nix you can use od -x and if on Windows run debug and use the d command to display the file as hex Using that you should be able to determine whether fields are fixed length or delimited by a particular character or tagged with a length prefix etc. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading binary files
Bob sorry, I misread your email and thought it said "read on" if the file was FORMATTED. It wasn't so I didn't (but should have). I read the complete thread and it is getting a little messy so I have extracted your questions and added some answers. I'd like to examine the file myself. We might save a lot of time and energy that way. If it is not very large would you attach it to your reply. If it is very large you could either copy just the first 1000 or so bytes, or send the whole thing thru www.yousendit.com. The file is around 800 Mb but I can't get hold of it until next week so suggest starting a new topic once I have a cut-down copy. Well, did you read on? What reactions do you have? I did (finally) read on and I am still a little confused, though less than before. I guess the word UNFORMATTED means that the file has no format though it presumably has some structure? One major hurdle is that I am not really sure about the difference between a Python binary file and a FORTRAN UNFORMATTED file so any pointers would be gratefully received The file looks like (where b = blank) (how it would look in notepad): bbDISTANCEbb10bFbbb0.00bbb1.00bbb2.00 If you analyze this with 2s8s2si2s1s you will see 2s matches bb, 8s matches DISTANCE, 2s matches bb, i matches . (\x40\x40\x40\x40). The i tells unpack to shove those 4 bytes unaltered into a Python integer, resulting in 538976288. You can verify that: >>> struct.unpack('i', '') (538976288,) Please either assure me you understand or are prepared for a more in depth tutorial. I now understand why Python gave me the results it did ... it looks like reading the FORTRAN file will be a non-trivial task so probably best to wait until I can post a copy of it. Thanks for your help Alun Griffiths ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Eliminating options
Hi! I'm using 32-bit Python on Windows 64-bit Vista (instead of 64-bit Python because I also use Numpy/Scipy which doesn't offer 64-bit versions yet). I'm doing some very simple text processing ie. given a string s, find a subtring using s.find(). But, the program doesn't find all instances of the substring specified in s.find(). I ran the program on a Windows 32-bit XP and the program works perfectly. Intuition says this should work on the 64-bit box but since it doesn't is it possible there is something bizarre going on with 32-bit Python running on a 64-bit OS? Dinesh___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading binary files
eShopping wrote: Bob I am trying to read UNFORMATTED files. The files also occur as formatted files and the format string I provided is the string used to write the formatted version. I can read the formatted version OK. I (naively) assumed that the same format string was used for both files, the only differences being whether the FORTRAN WRITE statement indicated unformatted or formatted. WRITE UNFORMATTED dump memory to disk with no formatting. That is why we must do some analysis of the file to see where the data has been placed, how long the floats are, and what "endian" is being used. I'd like to examine the file myself. We might save a lot of time and energy that way. If it is not very large would you attach it to your reply. If it is very large you could either copy just the first 1000 or so bytes, or send the whole thing thru www.yousendit.com. At 21:41 03/02/2009, bob gailer wrote: First question: are you trying to work with the file written UNFORMATTED? If so read on. Well, did you read on? What reactions do you have? eShopping wrote: Data format: TIME 1 F 0.0 DISTANCE 10 F 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 F=float, D=double, L=logical, S=string etc The first part of the file should contain a string (eg "TIME"), an integer (1) and another string (eg "F") so I tried using import struct in_file = open(file_name+".dat","rb") data = in_file.read() items = struct.unpack('sds', data) Now I get the error error: unpack requires a string argument of length 17 which has left me completely baffled! Did you open the file with mode 'b'? If not change that. You are passing the entire file to unpack when you should be giving it only the first "line". That's why is is complaining about the length. We need to figure out the lengths of the lines. Consider the first "line" TIME 1 F 0.0 There were (I assume) 4 FORTRAN variables written here: character integer character float. Without knowing the lengths of the character variables we are at a loss as to what the struct format should be. Do you know their lengths? Is the last float or double? Try this: print data[:40] You should see something like: TIME...\x01\x00\x00\x00...F...\x00\x00\x00\x00...DISTANCE...\n\x00\x00\x00 where ... means 0 or more intervening stuff. It might be that the \x01 and the \n are in other places, as we also have to deal with "byte order" issues. Please do this and report back your results. And also the FORTRAN variable types if you have access to them. Apologies if this is getting a bit messy but the files are at a remote location and I forgot to bring copies home. I don't have access to the original FORTRAN program so I tried to emulate the reading the data using the Python script below. AFAIK the FORTRAN format line for the header is (1X, 1X, A8, 1X, 1X, I6, 1X, 1X, A1). If the data following is a float it is written using n(1X, F6.2) where n is the number of records picked up from the preceding header. # test program to read binary data import struct # create dummy data data = [] for i in range(0,10): data.append(float(i)) # write data to binary file b_file = open("test.bin","wb") b_file.write(" %8s %6d %1s\n" % ("DISTANCE", len(data), "F")) for x in data: b_file.write(" %6.2f" % x) You are still confusing text vs binary. The above writes text regardless of the file mode. If the FORTRAN file was written UNFORMATTED then you are NOT emulating that with the above program. The character data is read back in just fine, since there is no translation involved in the writing nor in the reading. The integer len(data) is being written as its text (character) representation (translating binary to text) but being read back in without translation. Also all the floating point data is going out as text. The file looks like (where b = blank) (how it would look in notepad): bbDISTANCEbb10bFbbb0.00bbb1.00bbb2.00 If you analyze this with 2s8s2si2s1s you will see 2s matches bb, 8s matches DISTANCE, 2s matches bb, i matches . (\x40\x40\x40\x40). The i tells unpack to shove those 4 bytes unaltered into a Python integer, resulting in 538976288. You can verify that: >>> struct.unpack('i', '') (538976288,) Please either assure me you understand or are prepared for a more in depth tutorial. b_file.close() # read back data from file c_file = open("test.bin","rb") data = c_file.read() start, stop = 0, struct.calcsize("2s8s2si2s1s") items = struct.unpack("2s8s2si2s1s",data[start:stop]) print items print data[:40] I'm pretty sure that when I tried this at the other PC there were a bunch of \x00\x00 characters in the file but they don't appear in NotePad ... anyway, I thought the Python above would unpack the data but items appears as (' ', 'DISTANCE', ' ', 538976288, '10', ' ') which seems to be contain an extra item (538976288) Alun Griffiths -- Bob Gailer Chapel Hill NC 919-636-4239
Re: [Tutor] reading file, adding to each line, writing file
Hmm...thanks Kent. Could use such information myself. I did feel that my code was bloated or could be tweaked somehow. Ha...there i double posted again :( Am having trouble paying attention today. On Wed, Feb 4, 2009 at 5:42 PM, Kent Johnson wrote: > On Wed, Feb 4, 2009 at 10:18 AM, OkaMthembo wrote: > > The following is adapted from my humble text processing script that i use > at > > work for a recurring task of mine. Any excuse not to use Java all day :) > > > > There was an error with my other posts. Pardon the triple posting - won't > > happen again soon. > > > > > > > > file_1 = open('step2', 'r+') > > lines = file_1.readlines() > > sentences = [] > > for line in lines: > > if line: > > I don't think line will ever be empty, so this test is not needed. > > > sentences.insert(len(sentences), line + '-d') > > sentences.append(line + '-d') is simpler. Note this appends after the > newline so it is not really what the OP wants. > > > file_1.close() > > file_2 = open('pyout', 'w+') > > if len(sentences) > 0: > > This test is not needed, if sentences is empty the for statement won't > do anything. > > > for sentence in sentences: > > file_2.write(sentence) > > The loop could be replaced with > file_2.writelines(sentences) > > Kent > -- Lloyd Dube ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading file, adding to each line, writing file
Hello Arthur, not there yet A.T.Hofkamp wrote: The simplest solution would be to construct a new line from the old one directly below the 'while', for example line2 = line[:-1] + " -d\n" followed by writing line2 to disk. Actually, I don't quite understand. You want me to put line2 = line[:-1] + " -d\n" right beneath the 'while', that is, without indenting it?? Never seen that before... Here is my latest try, which works: # add " -d" to each line of a textfile infile = open("step3", 'r') # open file for appending -- returns a file object outfile = open("pyout","a") # open file for appending -- returns a file object line = infile.readline()# Invokes readline() method on file for i in line: line2 = line[:-1] + " -d\n" outfile.write(line2), # trailing ',' omits newline character line = infile.readline() infile.close() outfile.close() print "done!" But I clearly still don't understand my own code. In particular I don't understand why I have to use infile.readline() twice, once before the for loop, and once inside it. Finally: changing the line "for i in line:" for "while line:" will freeze the machine, filling my hard disk. Any ideas? David ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading file, adding to each line, writing file
On Wed, Feb 4, 2009 at 10:18 AM, OkaMthembo wrote: > The following is adapted from my humble text processing script that i use at > work for a recurring task of mine. Any excuse not to use Java all day :) > > There was an error with my other posts. Pardon the triple posting - won't > happen again soon. > > > > file_1 = open('step2', 'r+') > lines = file_1.readlines() > sentences = [] > for line in lines: > if line: I don't think line will ever be empty, so this test is not needed. > sentences.insert(len(sentences), line + '-d') sentences.append(line + '-d') is simpler. Note this appends after the newline so it is not really what the OP wants. > file_1.close() > file_2 = open('pyout', 'w+') > if len(sentences) > 0: This test is not needed, if sentences is empty the for statement won't do anything. > for sentence in sentences: > file_2.write(sentence) The loop could be replaced with file_2.writelines(sentences) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading file, adding to each line, writing file
The following is adapted from my humble text processing script that i use at work for a recurring task of mine. Any excuse not to use Java all day :) There was an error with my other posts. Pardon the triple posting - won't happen again soon. file_1 = open('step2', 'r+') lines = file_1.readlines() sentences = [] for line in lines: if line: sentences.insert(len(sentences), line + '-d') file_1.close() file_2 = open('pyout', 'w+') if len(sentences) > 0: for sentence in sentences: file_2.write(sentence) file_2.close() On Wed, Feb 4, 2009 at 4:30 PM, David wrote: > Hello everybody, > > I have easily spent some four hours on this problem, and I am now asking > for rescue. > > Here is what I am trying to do: I have a file ("step2", with some 30 or so > lines. To each line I would like to add " -d" at the end. Finally, I want to > save the file under another name ("pyout". > So far I have managed to read the file, line by line, and save it under > another name: > > > > # add " -d" to each line of a textfile > > infile = open("step2", 'r') # open file for appending > outfile = open("pyout","a") # open file for appending > > line = infile.readline()# Invokes readline() method on file > while line: >outfile.write(line),# trailing ',' omits newline character >line = infile.readline() > > infile.close() > outfile.close() > > > > As I said, before writing to file "pyout" I would like to append the string > " -d" to each line. But how, where? I can't append to strings (which the > lines gained with infile.readline() seem be), and my trial and error > approach has brought me nothing but a headache. > > Thanks for your help! > > David > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Dube ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading file, adding to each line, writing file
The following is adapted from my humble text processing script that i use at work for a recurring task of mine. Any excuse not to use Java all day :) file_1 = open('step2', 'r+') lines = file_1.readlines() sentences = [] for line in lines: if line: sentences.insert(line + '-d') file_1.close() file_2 = open('pyout', 'w+') if len(sentences) > 0: for sentence in sentences: file_2.write(sentence) file_2.close() On Wed, Feb 4, 2009 at 4:30 PM, David wrote: > Hello everybody, > > I have easily spent some four hours on this problem, and I am now asking > for rescue. > > Here is what I am trying to do: I have a file ("step2", with some 30 or so > lines. To each line I would like to add " -d" at the end. Finally, I want to > save the file under another name ("pyout". > So far I have managed to read the file, line by line, and save it under > another name: > > > > # add " -d" to each line of a textfile > > infile = open("step2", 'r') # open file for appending > outfile = open("pyout","a") # open file for appending > > line = infile.readline()# Invokes readline() method on file > while line: >outfile.write(line),# trailing ',' omits newline character >line = infile.readline() > > infile.close() > outfile.close() > > > > As I said, before writing to file "pyout" I would like to append the string > " -d" to each line. But how, where? I can't append to strings (which the > lines gained with infile.readline() seem be), and my trial and error > approach has brought me nothing but a headache. > > Thanks for your help! > > David > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Dube ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading file, adding to each line, writing file
On Wed, Feb 4, 2009 at 3:30 PM, David wrote: > Hello everybody, > > I have easily spent some four hours on this problem, and I am now asking for > rescue. > > Here is what I am trying to do: I have a file ("step2", with some 30 or so > lines. To each line I would like to add " -d" at the end. Finally, I want to > save the file under another name ("pyout". > So far I have managed to read the file, line by line, and save it under > another name: > > > > # add " -d" to each line of a textfile > > infile = open("step2", 'r') # open file for appending > outfile = open("pyout","a") # open file for appending > > line = infile.readline()# Invokes readline() method on file > while line: >outfile.write(line),# trailing ',' omits newline character >line = infile.readline() > > infile.close() > outfile.close() > > > > As I said, before writing to file "pyout" I would like to append the string > " -d" to each line. But how, where? I can't append to strings (which the > lines gained with infile.readline() seem be), and my trial and error > approach has brought me nothing but a headache. You cannot append to strings, but you can add to them! So the first step would be: > # add " -d" to each line of a textfile infile = open("step2", 'r') # open file for reading outfile = open("pyout","a") # open file for appending line = infile.readline()# Invokes readline() method on file while line: outfile.write(line+" -d"),# trailing ',' omits newline character line = infile.readline() infile.close() outfile.close() However, that doesn't work fine, because the newline is at the end of the line, and thus the -d is coming at the beginning. To work that out, we use string.strip() which allows us to remove certain characters from the beginning and end of a string: # add " -d" to each line of a textfile infile = open("step2", 'r') # open file for reading outfile = open("pyout","a") # open file for appending line = infile.readline()# Invokes readline() method on file while line: outfile.write(line.strip("\n")+" -d\n") line = infile.readline() infile.close() outfile.close() By the way, a somewhat more elegant method (in my opinion at least) is to use readlines(), which gives a generator of the lines in a file, rather than readline(): # add " -d" to each line of a textfile infile = open("step2", 'r') # open file for appending outfile = open("pyout","a") # open file for appending for line in infile.readlines(): outfile.write(line.strip("\n")+" -k\n") infile.close() outfile.close() Yet another method would be a combination of read and replace: # add " -d" to each line of a textfile infile = open("step2", 'r') # open file for appending outfile = open("pyout","a") # open file for appending outfile.write(infile.read().replace("\n"," -d\n")) infile.close() outfile.close() However, this is sensitive to the presence or absence of a newline after the last line. -- André Engels, andreeng...@gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading file, adding to each line, writing file
Hello Albert, thanks for your answer! A.T.Hofkamp wrote: The 'while' loop can be replaced by a 'for' loop, like for line in infile: outfile.write(line) I first was thinking of/experimenting with a 'for' loop, but what I originally had in mind was to combine the 'for' loop with readline() -- which Python disallows. So I changed to a 'while' loop. The simplest solution would be to construct a new line from the old one directly below the 'while', for example line2 = line[:-1] + " -d\n" followed by writing line2 to disk. The question that arises however is, what should be done with a line like "bla bla \n" Do you want "bla bla -d\n" or do you want "bla bla -d\n" here? I want "bla bla" -d\n ;-) Let me try your suggestions out! Cheers, David ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [Visualpython-users] VPython and Tkinter
In Visual 3, there is an example program (Tk-visual.py, if I remember correctly) which shows a Tk window controlling actions in a separate Visual window. In Visual 5, I believe that this program would still work on Windows and Linux, but because there seems to be no way to make this work in the Carbon-based Mac version, the application was removed from the set of examples, which are platform-independent. Bruce Sherwood Mr Gerard Kelly wrote: Is there a way to make separate VPython and Tkinter windows run simultaneously from the one program? Or to have the VPython window run inside a Tkinter toplevel? If I have a program that uses both, it seems that one window has to close before the other will start running. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] reading file, adding to each line, writing file
David wrote: line = infile.readline()# Invokes readline() method on file while line: outfile.write(line),# trailing ',' omits newline character line = infile.readline() The 'while' loop can be replaced by a 'for' loop, like for line in infile: outfile.write(line) infile.close() outfile.close() As I said, before writing to file "pyout" I would like to append the string " -d" to each line. But how, where? I can't append to strings (which the lines gained with infile.readline() seem be), and my trial and error approach has brought me nothing but a headache. readline() literally reads a line, including the terminating \n at the end. (the end-of-file indication uses the empty string. By returning the terminating \n as well, an empty line becomes a "\n" string, so you can distinguish between both cases). The simplest solution would be to construct a new line from the old one directly below the 'while', for example line2 = line[:-1] + " -d\n" followed by writing line2 to disk. The question that arises however is, what should be done with a line like "bla bla \n" Do you want "bla bla -d\n" or do you want "bla bla -d\n" here? If the latter, you may want to use str.rstrip() that deletes all white-space from the end of the line, like line2 = line.rstrip() + " -d\n" Sincerely, Albert ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] reading file, adding to each line, writing file
Hello everybody, I have easily spent some four hours on this problem, and I am now asking for rescue. Here is what I am trying to do: I have a file ("step2", with some 30 or so lines. To each line I would like to add " -d" at the end. Finally, I want to save the file under another name ("pyout". So far I have managed to read the file, line by line, and save it under another name: # add " -d" to each line of a textfile infile = open("step2", 'r') # open file for appending outfile = open("pyout","a") # open file for appending line = infile.readline()# Invokes readline() method on file while line: outfile.write(line),# trailing ',' omits newline character line = infile.readline() infile.close() outfile.close() As I said, before writing to file "pyout" I would like to append the string " -d" to each line. But how, where? I can't append to strings (which the lines gained with infile.readline() seem be), and my trial and error approach has brought me nothing but a headache. Thanks for your help! David ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] re division problem
hi I modified my function ' vertical' by adding a few characters to eliminate the division problem. def vertical(columns): if columns>7: columns=7 import string v=string.printable v=v.replace('\n','') v=v.replace('\t','') if len(v)%columns !=0: v=v+ v[:columns-(len(v)%columns)] for x in range(len(v)/columns): for y in range(x,len(v),len(v)/columns): print v[y],'=','%3d'%ord(v[y]),' '*3, print Thank you Prasad ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] inheriting different builtin types
Hello, I have a strange problem and cannot see a clear method to solve it. I would like to build a custom type that is able to add some informational attributes and a bunch attribute to a main "value". The outline is then: class Custom(X): def __init__(self, value, more): X.__init__(self) The base class is here to inherit value's behaviour and to avoid writing obj.value all the time. For this type will be heavily used by client code. The point is, this value may actually be of several builtin types. Logically, X is value.__class__. I imagine there are solutions using a factory, or __new__, or maybe metaclass (never done yet)? I cannot find a working method myself. Denis -- la vida e estranya ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sort of database & "family tree" question
Alan Gauld schreef: "spir" wrote > The current way of reading the data is this: > > def get_info(person) >infoDic = {} >infoDic['first'] = parser.get(person, 'firstName') >infoDic['last'] = parser.get(person, 'lastName') >infoDic['father'] = parser.get(person, 'father') >infoDic['mother'] = parser.get(person, 'mother') >return infoDic TYhis is almost the same but you are using a dict. A sligtly more readable version is to define a class Person: class Person: def __init__(self, parser): self.first = parser.get(person, 'firstName') Hey Alan, thanks for that explanation! But the class you gave, does almost the same thing as my function. We both store the info in a dic, so to retrieve info for a certain person, we both have to do the same thing. Or am I missing something here? If so, I would love to hear it! Because I have to admit that when I program, I rarely use classes. Yes, its not normal and the class probably should be called ParsedPerson or somesuch. I ws trying to mimic the current code style as much as possible, that was the reason for the decision. Normally I would agree with you and use: class Person: def __init__(self, first, last, father, mother): self.first = first self.last = last self.father = father self.mother = mother If I do it like this, I will have to parse all the data from the file and then send them to this class and then call this class again to retrieve it. Then I like my function better. But again, I would love to hear if I'm wrong. Timo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sort of database & "family tree" question
"spir" wrote > The current way of reading the data is this: > > def get_info(person) >infoDic = {} >infoDic['first'] = parser.get(person, 'firstName') >infoDic['last'] = parser.get(person, 'lastName') >infoDic['father'] = parser.get(person, 'father') >infoDic['mother'] = parser.get(person, 'mother') >return infoDic TYhis is almost the same but you are using a dict. A sligtly more readable version is to define a class Person: class Person: def __init__(self, parser): self.first = parser.get(person, 'firstName') Maybe I don't get the point, but I find it strange to make Person dependant not only of the data storage format, but also of the parsing technique. Yes, its not normal and the class probably should be called ParsedPerson or somesuch. I ws trying to mimic the current code style as much as possible, that was the reason for the decision. Normally I would agree with you and use: class Person: def __init__(self, first, last, father, mother): self.first = first self.last = last self.father = father self.mother = mother Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sort of database & "family tree" question
Le Wed, 4 Feb 2009 01:16:17 + (GMT), ALAN GAULD a écrit : > > > And I assume you are reading these into a Person class and > > > storing these classes in a persons dictionary? > > > > Can you explain this a little more for me please? > > > Sure. > (I didn't notice this on gmane so apologies if others already answered) > > > The current way of reading the data is this: > > > > parser = ConfigParser.ConfigParser() > > parser.read(personFile) > > > > def get_info(person) > >infoDic = {} > >infoDic['first'] = parser.get(person, 'firstName') > >infoDic['last'] = parser.get(person, 'lastName') > >infoDic['father'] = parser.get(person, 'father') > >infoDic['mother'] = parser.get(person, 'mother') > >return infoDic > > TYhis is almost the same but you are using a dict. A sligtly more readable > version is to define a class Person: > > class Person: > def __init__(self, parser): > self.first = parser.get(person, 'firstName') > self.last = parser.get(person, 'lastName') > self.father = parser.get(person, 'father') > self.mother = parser.get(person, 'mother') > Maybe I don't get the point, but I find it strange to make Person dependant not only of the data storage format, but also of the parsing technique. I would have written __init__ as usual so as to require the parser to deliver proper information -- not the contrary: class Person: def __init__(self, first, last, father, mother): self.first = first self.last = last self.father = father self.mother = mother If the format evoluates --> adapt the parser If the parser changes --> adapt it to Person's interface But the Person model has its own meaning. It should change only if the application's specification evoluates. Denis -- la vida e estranya ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] VPython and Tkinter
Is there a way to make separate VPython and Tkinter windows run simultaneously from the one program? Or to have the VPython window run inside a Tkinter toplevel? If I have a program that uses both, it seems that one window has to close before the other will start running. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Parsing suggestion? (CUE file) -- identify result
Le Tue, 3 Feb 2009 17:36:41 -0500, Kent Johnson a écrit : > I think your use of the csv module is fine. What I really meant to say > was more like, I would have looked to pyparsing to solve the same > problem, and if you want a parser that parses the file into meaningful > records, then it might still be worth a look. This would require heavy use of the setResultsName() method to attach "semantic tags" to the parse results; so that when you dig into them you know what each snippet is -- without the need of partial reparsing ;-) The point can be illustrated with the simple case of parsing arithmetic operations. Imagine each operand of a '+' can be a (litteral) number, a symbol (name), a grouped (parenthesized) sub-operation, an operation of higher priority. The result beeing of the form [op1, '+', op2] There is no other way to know what kind of thing op1 and op2 are, if they don't themselves carry the information, than re-examining them. Which has already beeing done while parsing. (The information needed is the name of the parsing rule used to yield the result.) Denis > > Kent -- la vida e estranya ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor