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

Kent Johnson kent37 at tds.net
Sun May 25 14:59:40 CEST 2008


On Sat, May 24, 2008 at 7:09 PM, Jason Conner <jasonbconner at gmail.com> wrote:

> def loadItem(self, objectToLoad):
>     wordList = []
>     fobj = open('/home/jason.conner/Documents/Python/objectconfig.txt', 'r')
>
>     for line in fobj:
>         if line == objectToLoad:
>             wordList.append(line)
>             for i in range(5):
>                 wordList.append(fobj.next())
>
> Though it did take me a few minutes to figure out that I needed to include
> the \n in the objectToLoad variable to get it to work in its present form,
> it works great. Thanks for all your help!

Yes, the lines you get from iterating the file contain the trailing
newlines. A simple fix (which strips *all* whitespace from both ends
of the line) is to say
  line = line.strip()
You can be more restrictive if you want, for example
  line = line.rstrip('\r\n')
will strip only carriage returns and line feeds from the end (right
side) of line.

Note that wordList will also include newlines in its entries. You
might want to use some variation of
  wordList.append(fobj.next().strip())

Kent


More information about the Tutor mailing list