12

In Python 2, file objects had an xreadlines() method which returned an iterator that would read the file one line at a time. In Python 3, the xreadlines() method no longer exists, and realines() still returns a list (not an iterator). Does Python 3 has something similar to xreadlines()?

I know I can do

for line in f:

instead of

for line in f.xreadlines():

But I would also like to use xreadlines() without a for loop:

print(f.xreadlines()[7]) #read lines 0 to 7 and prints line 7
asheeshr
  • 4,088
  • 6
  • 31
  • 50
snakile
  • 52,936
  • 62
  • 169
  • 241
  • 1
    You *cannot* index an iterator. `zip([1,2,3],[4,5,6])[0]` -> error. – kennytm Aug 22 '10 at 14:23
  • @KennyTM Your'e right. I deleted the part of me saying "you can index an iterator". I thought I can index an iterator because I can do range(10)[7], but it doesn't mean I can index an iterator. Thanks. – snakile Aug 22 '10 at 15:37

2 Answers2

17

The file object itself is already an iterable.

>>> f = open('1.txt')
>>> f
<_io.TextIOWrapper name='1.txt' encoding='UTF-8'>
>>> next(f)
'1,B,-0.0522642316338,0.997268450092\n'
>>> next(f)
'2,B,-0.081127897359,2.05114559572\n'

Use itertools.islice to get an arbitrary element from an iterable.

>>> f.seek(0)
0
>>> next(islice(f, 7, None))
'8,A,-0.0518101108474,12.094341554\n'
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
1

how about this (generator expression):

>>> f = open("r2h_jvs")
>>> h = (x for x in f)
>>> type(h)
<type 'generator'>`
Albert Visser
  • 1,124
  • 6
  • 5