[Tutor] Reading only a few specific lines of a file
John Fouhy
john at fouhy.net
Fri May 23 03:03:11 CEST 2008
On 23/05/2008, Jason Conner <jasonbconner at gmail.com> wrote:
Hi Jason,
> def loadItem(self, objectToLoad):
> x = 0
> wordList = []
> fobj = file()
> fobj.open("itemconfig.txt", 'rU')
>
> for line in fobj.readline():
In recent pythons, you can write this better as:
for line in fobj:
Once you've done this, you can use .next() to advance the iterator. e.g.:
for line in fobj:
if line == objectToLoad:
wordList.append(line)
wordList.append(fobj.next())
This will save the line that matched and the line following it. Note
that this means you won't check the second line --- you can maybe
visualise this with a simpler example:
>>> a = []
>>> nums = iter(range(10))
>>> for i in nums:
... a.append((i, nums.next()))
...
>>> a
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
--
John.
More information about the Tutor
mailing list