在python中使用f.tell()索引文件

2024-09-24 22:22:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图索引一个大文件,每行由5列组成。第一列将是键,并对其进行排序(假设只有17列)。我想生成一个字典,它告诉每个键值的起始位置。所以我要做的是:

fmaps = open('file.txt','r')
pos = fmaps.tell()
ln = fmaps.readline()
chrDict = {ln.split()[0]:pos}



for ln in fmaps:

    if not chrDict.has_key(ln.split()[0]):
           pos = fmaps.tell() 
           chrDict[ln.split()[0]] = pos

但是,当我打开文件时

^{pr2}$

我看到,除了第一个位置从开始是0字节外,其他位置都完全偏离了原点。在

有人知道for循环中的迭代对文件中的位置做了什么吗?在


Tags: 文件postxtforreadline字典排序open
2条回答

当使用file对象作为迭代器时,Python会进行内部缓冲,这会扭曲tell()的结果。只需继续使用readline。还有

(编辑:哎呀,我第一次没看懂你的问题!)在

  • 按照@falsetru的建议阅读二进制文件
  • 第一次读的时候你不需要特殊情况

这应该可以做到:

chrDict = {}
with open('file.txt','rb') as fmaps:
    while True:
        pos = fmaps.tell()
        ln = fmaps.readline()
        if not ln:
            break
        key = ln.split()[0]
        if key not in chrDict:
            chrDict[key] = pos

根据^{} documentation

Note On Windows, tell() can return illegal values (after an fgets()) when reading files with Unix-style line-endings. Use binary mode ('rb') to circumvent this problem.

将模式'r'替换为'rb'。在

相关问题 更多 >