[Tutor] Reading only a few specific lines of a file

Alan Gauld alan.gauld at btinternet.com
Fri May 23 12:49:37 CEST 2008


"Jason Conner" <jasonbconner at gmail.com> 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


HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list