简体   繁体   English

什么时候是使用readline()的好时机?

[英]When is a good time to use readline()?

Many have asked how to read a file line by line in Python. 许多人已经问过如何在Python中逐行读取文件。 And, instead of using readline(), many have recommended the following way: 而且,许多人建议采用以下方式,而不是使用readline()。

with open('myfile.py') as f:
  for line in f:

Also, some said that readlines() is not an efficient way to use memory because it reads everything at once. 另外,有人说readlines()不是一种使用内存的有效方法,因为它一次读取所有内容。

Is there any time that I should use readline() over the recommended method above? 有没有时间我应该使用readline()而不是上面推荐的方法? Or, should I forget about this function?? 或者,我应该忘记这个功能??

You should use readline() only if using for is not possible or useful. 仅当使用for不可行或无用时,才应使用readline()

Example: The file contains a fixed header like 示例:该文件包含一个固定的标题

  • 1st line: Fixed identification string of file type 第1行:修复了文件类型的标识字符串
  • 2nd line: filetype version identifier 第二行:文件类型版本标识符
  • 3rd line: Size of following binary data 第3行:以下二进制数据的大小
  • Followed by: binary data of given amount 其次是:给定数量的二进制数据

In such a case a for -loop would need some kind of line count variable to remember which line is currently processed. 在这种情况下, for -loop需要某种行计数变量来记住当前处理的行。

This would end up in code like this: 这将最终在这样的代码中:

for i, line in enumerate(f):
    if i == 0:
        if line != "Foobar file format\n":
            raise Exception("Wrong file format")
    elif i == 1:
        if int(line) > 4:
            raise Exception("File format version too new")
    elif i == 2:
        size = int(line)
        break

instead of simply this 而不仅仅是这个

if f.readline() != "Foobar file format\n":
    raise Exception("Wrong file format")

if int(f.readline()) > 4:
    raise Exception("File format version too new")

size = int(f.readline())

(some error checks omitted for clarity) (为清楚起见省略了一些错误检查)

如果你想一次一个地使用每一行,而不是它们出现在文件内部的顺序(即第3-> 2-> 6-> 5->等),则读取线可能很有用。 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM