代码之家  ›  专栏  ›  技术社区  ›  snakile

在python3中,什么替代了xreadlines()?

  •  8
  • snakile  · 技术社区  · 14 年前

    在python2中,file对象有一个xreadlines()方法,该方法返回一个迭代器,该迭代器一次读取一行文件。在python3中,xreadlines()方法不再存在,realines()仍然返回一个列表(不是迭代器)。python3有类似于xreadlines()的东西吗?

    我知道我能做到

    for line in f:
    

    而不是

    for line in f.xreadlines():
    

    但我也希望使用没有for循环的xreadlines():

    print(f.xreadlines()[7]) #read lines 0 to 7 and prints line 7
    
    2 回复  |  直到 11 年前
        1
  •  16
  •   kennytm    14 年前

    文件对象本身已经是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

    >>> f.seek(0)
    0
    >>> next(islice(f, 7, None))
    '8,A,-0.0518101108474,12.094341554\n'
    
        2
  •  1
  •   Albert Visser    14 年前

    这个(生成器表达式)怎么样:

    >>> f = open("r2h_jvs")
    >>> h = (x for x in f)
    >>> type(h)
    <type 'generator'>`