【问题标题】:What substitutes xreadlines() in Python 3?在 Python 3 中用什么替代 xreadlines()?
【发布时间】:2011-04-02 06:15:05
【问题描述】:

在 Python 2 中,文件对象有一个 xreadlines() 方法,该方法返回一个迭代器,该迭代器将一次读取文件一行。在 Python 3 中,xreadlines() 方法不再存在,realines() 仍然返回一个列表(不是迭代器)。 Python 3 是否有类似于 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

【问题讨论】:

  • 不能索引一个迭代器。 zip([1,2,3],[4,5,6])[0] -> 错误。
  • @KennyTM 你是对的。我删除了我说“你可以索引一个迭代器”的部分。我以为我可以索引一个迭代器,因为我可以做 range(10)[7],但这并不意味着我可以索引一个迭代器。谢谢。

标签: python iterator python-3.x readlines


【解决方案1】:

文件对象本身已经是一个可迭代对象。

>>> 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】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-01-30
      • 2018-10-23
      • 2023-03-07
      • 1970-01-01
      • 2011-05-21
      • 2020-04-01
      • 2014-11-30
      • 2013-01-04
      • 1970-01-01
      相关资源
      最近更新 更多