我试图索引一个大文件,每行由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循环中的迭代对文件中的位置做了什么吗?在
当使用file对象作为迭代器时,Python会进行内部缓冲,这会扭曲tell()的结果。只需继续使用readline。还有
(编辑:哎呀,我第一次没看懂你的问题!)在
这应该可以做到:
根据^{} documentation :
将模式
'r'
替换为'rb'
。在相关问题 更多 >
编程相关推荐