(I'm sorry for the duplicate, Alan.) On Fri, May 23, 2008 3:49 am, Alan Gauld wrote:
> "Jason Conner" <[EMAIL PROTECTED]> wrote > > >> building a program that will take a text file, search for a string in >> that text file. Once it finds the string its looking for, I want to put >> the next five lines of text into a variable. Here's what I have so far: >> >> def loadItem(self, objectToLoad): x = 0 wordList = [] fobj = file() > > This does nothing. file() is just an alias for open() > > > >> fobj.open("itemconfig.txt", 'rU') >> >> for line in fobj.readline(): > > And you can iterate over the file itself so this could become: > > > for line in file(("itemconfig.txt", 'rU'): > > >> if line == objectToLoad: while x != 5 for word in line.split(): >> wordList.append(word) x += 1 > > This isn't quite what you said above in that you didn't mention > storing the individual words... > >> >> thing = item(wordList[0], wordList[1], wordList[2], wordList[3], >> wordList[4]) > > But this could just be: > > > thing = line.split[:5] # use slicing to get first 4 items > >> itemList.append(thing) > > or even make it all one line here... > > Now to get the next 4 lines as well set a flag/counter. say linecount. > Set it to 0 at the top then > > > linecount = 0 for line in file("itemconfig.txt", 'rU'): if line == > objectToLoad or linecount > 0: if linecount == 0: linecount = 5 # set > linecount on first line itemList.append(line.split()[:5]) > linecount -= 1 I always go for readability. So I like "for x in range(5):" to go 5 times. I'm not sure what we should be doing 5 times either. Similarly, for readability, I choose the if/elif/else form of switch replacement. Also, I don't like to see the obfuscated forms of the conditional operator. Heck, I'm not even crazy about the Python conditional in 2.5. I like to say "The point of a programming language is to communicate with other engineers (in a language that also the computer understands)." I hope you like these thoughts. Marilyn Davis > > > 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 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor