当使用Python3迭代文件时,如何找到文件光标的位置?
在Python 2.7中,使用tell()
函数很容易就可以找到,但在Python3中将会抛出一个OSError
异常:
Traceback (most recent call last):
File "foo.py", line 113, in check_file
pos = infile.tell()
OSError: telling position disabled by next() call
我的使用情况是为了读取大型CSV文件而制作进度条。计算总行数过于昂贵并需要额外的步骤。一个近似值已经足够有用了,我不关心缓冲区或其他噪声来源,我想知道它需要10秒钟还是10分钟。以下是复现问题的简单代码。在Python 2.7上按预期工作,但在Python 3上会出错:
file_size = os.stat(path).st_size
with open(path, "r") as infile:
reader = csv.reader(infile)
for row in reader:
pos = infile.tell() # OSError: telling position disabled by next() call
print("At byte {} of {}".format(pos, file_size))
这个答案https://dev59.com/IF0b5IYBdhLWcg3wGN0s#29641787表明问题在于
next()
方法在迭代期间禁用了tell()
。替代方法是手动逐行读取,但该代码位于CSV模块中,因此我无法使用它。我也不明白Python 3禁用tell()
的好处在哪里。
那么,在Python 3中迭代文件行时查找字节偏移量的首选方法是什么?
enumerate
并返回行号。这样,您可以向用户提供有用的信息,而无需对文件进行两次遍历。 - Maarten Fabré