我需要一次读取最多N行读取一个大文件,直到EOF.在Python中最有效的方法是什么?就像是:
with open(filename, 'r') as infile:
while not EOF:
lines = [get next N lines]
process(lines)
Run Code Online (Sandbox Code Playgroud) 我无法确定何时使用 file.readline 到达 python 中的文件末尾
fi = open('myfile.txt', 'r')
line = fi.readline()
if line == EOF: //or something similar
dosomething()
Run Code Online (Sandbox Code Playgroud)
c = fp.read() if c is None: 将不起作用,因为那样我将丢失下一行的数据,如果一行只有回车,我将错过一个空行。
我看了几十个或相关的帖子,它们都只是使用了固有的循环,当它们完成时就会中断。我没有循环,所以这对我不起作用。此外,我在 GB 中有 100 行的文件大小。一个脚本可能会花费数天时间来处理一个文件。所以我需要知道如何判断我何时在 python3 中的文件末尾。任何帮助表示赞赏。谢谢!
我知道逐行迭代一个文件,我可以使用这样的构造:
for line in file:
do stuff
Run Code Online (Sandbox Code Playgroud)
但是,如果我在for中的某个地方也有一个break语句,一旦我不在for块中,我该如何判断是否是让我退出for for构造的中断OR它是因为我命中了文件的末尾已经?
我尝试了如何找出文件是否在其`eof`的建议?:
f.tell() == os.fstat(f.fileno()).st_size
Run Code Online (Sandbox Code Playgroud)
但这似乎不适用于我的Windows机器.基本上,f.tell()总是返回文件的大小.
我们考虑一个文件:
$ echo -e """This is a foo bar sentence .\nAnd this is the first txtfile in the corpus .""" > test.txt
$ cat test.txt
This is a foo bar sentence .
And this is the first txtfile in the corpus .
Run Code Online (Sandbox Code Playgroud)
当我想逐个阅读文件时,我可以做/sf/answers/1755011331/:
>>> fin = open('test.txt')
>>> while fin.read(1):
... fin.seek(-1,1)
... print fin.read(1),
...
T h i s i s a f o o b a r s e n t e n c e . …Run Code Online (Sandbox Code Playgroud)