【问题标题】:Alternative to readline in PythonPython 中 readline 的替代方案
【发布时间】:2018-11-30 02:05:37
【问题描述】:

在 Python 中哪个是 readline 的最佳替代方案?

我想逐行读取类似文件的对象。这个类文件对象包含以下方法:

  • read():从当前偏移处的类文件对象中读取一个字节串。
  • seek():寻找文件类对象内的偏移量。
  • get_offset():将当前偏移量检索到类文件对象中。
  • get_size():获取类文件对象的大小。

我无法阅读大于 2GB 的文件的完整文本,所以我不能这样做:

   for line in file_object.read():
      dostuff(line)

我测试了一些逐行读取的方法:这些方法适用于非常小的文件,但对于大文件来说速度很慢。无论如何,这些都比 File readline() 慢得多。 这是我尝试过的一个例子:

text = ''
while True:
  char = file_object.read(1)
  if char == '':
    return ''
  text += buffer + char
  if char == '\n':
    pos_newline = text.find('\n')
    current_offset += pos_newline + 1
    buffer = text[pos_newline + 1:]
    line = text[:pos_newline]
    return line

我还尝试一次读取 10/50/100 个字符。

我只能使用标准库。

编辑:“类文件”不可迭代。

【问题讨论】:

  • 你不需要.readline()。直接遍历文件指针,适合逐行迭代的情况。
  • @RockyLi 因为不是文件,所以是“类文件”。
  • @Austin 文件指针?你这是什么意思?
  • @S.Martinelli,这里的文件指针是file_object。
  • @Austin 文件对象不可迭代。

标签: python readline


【解决方案1】:

你可以分块阅读

while True:
    chunk = f.read(CHUNK_SIZE)
    if chunk == '':
        # we've reached the end
        break
    # process chunk

但很有可能您拥有的任何类似文件的对象都可以直接迭代以获取行。

for line in f:
    # I don't have readline, but I work anyway hee hee!

【讨论】:

猜你喜欢
  • 2010-12-25
  • 1970-01-01
  • 2021-04-13
  • 2011-02-09
  • 2015-06-19
  • 2011-02-16
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多