mgi*_*son 5 python file io-buffering
我正在尝试“映射”一个非常大的 ascii 文件。基本上,我会读取行,直到找到某个标签,然后我想知道该标签的位置,以便稍后再次查找它以提取相关数据。
from itertools import dropwhile
with open(datafile) as fin:
ifin = dropwhile(lambda x:not x.startswith('Foo'), fin)
header = next(ifin)
position = fin.tell()
Run Code Online (Sandbox Code Playgroud)
现在这tell并没有给我正确的位置。这个问题以前已经以各种形式被问过。原因大概是因为 python 正在缓冲文件对象。所以,python 告诉我它的文件指针在哪里,而不是我的文件指针在哪里。 我不想关闭这个缓冲......这里的性能很重要。然而,如果知道是否有一种方法可以确定 python 选择缓冲多少字节,那就太好了。在我的实际应用程序中,只要我关闭以 开头的行Foo,就没有关系。我可以到处写几行。所以,我实际上计划做的是这样的:
position = fin.tell() - buffer_size(fin)
Run Code Online (Sandbox Code Playgroud)
有什么办法可以找到缓冲区大小吗?
对我来说,缓冲区大小在 Cpython 中被硬编码为 8192。据我所知,除了打开文件时读取一行之外,没有其他方法可以从 python 接口获取这个数字。 ,执行 af.tell()计算出 python 实际读取了多少数据,然后在继续之前返回到文件的开头。
with open(datafile) as fin:
next(fin)
bufsize = fin.tell()
fin.seek(0)
ifin = dropwhile(lambda x:not x.startswith('Foo'), fin)
header = next(ifin)
position = fin.tell()
Run Code Online (Sandbox Code Playgroud)
当然,如果第一行长度超过 8192 字节,则会失败,但这对我的应用程序没有任何实际影响。