我正在尝试读取大型文本文件的前100行。下面显示了执行此操作的简单代码。然而,挑战在于,我必须警惕腐败或其他没有任何换行符的文件(是的,人们以某种方式设法生成这些文件)。在这些情况下,我仍然希望阅读数据(因为我需要看看那里发生了什么),但将其限制为n字节。使用readline读取的限制数量
我能想到的唯一方法就是通过char读取char文件。除了速度慢(可能不是一个问题,只有100行),我担心当遇到使用非ASCII编码的文件时会遇到麻烦。
是否可以限制使用readline()读取的字节?还是有更好的方法来处理这个问题?
line_count = 0
with open(filepath, 'r') as f:
for line in f:
line_count += 1
print('{0}: {1}'.format(line_count, line))
if line_count == 100:
break
编辑:
作为@Fredrik正确地指出,的ReadLine()接受限制字符的数目读(我认为这是一个缓冲器大小参数)的精氨酸。所以,我的目的,下面的工作得很好:
max_bytes = 1024*1024
bytes_read = 0
fo = open(filepath, "r")
line = fo.readline(max_bytes)
bytes_read += len(line)
line_count = 0
while line != '':
line_count += 1
print('{0}: {1}'.format(line_count, line))
if (line_count == 100) or (bytes_read == max_bytes):
break
else:
line = fo.readline(max_bytes - bytes_read)
bytes_read += len(line)
有关'file'对象上可用方法的更多信息,读者可以查看文档ntation [here](https://docs.python.org/2/library/stdtypes.html#file-objects)。 'readlines()'的同义词 – Monkpit
。最佳方法见'http:// stupidpythonideas.blogspot.fr/2013/06/readlines-considered-silly.html'。 –
就是这样。我问这个问题感到很愚蠢。不知何故,我在脑海中得知readline()的大小参数只是一个初始的缓冲区猜测,而不是读取字符数量的限制。如果对任何人都有用,可以使用最终解决方案进行编辑。 – Gadzooks34