Skip to main content
 首页 » 编程设计

python之如何在python中获取文件中的字节偏移量

2025年05月04日14EasonJim

我正在使用 hadoop 和 python 制作倒排索引。 我想知道如何在 python 中包含行/字的字节偏移量。 我需要这样的东西

hello hello.txt@1124 

我需要制作完整倒排索引的位置。 请帮忙。

请您参考如下方法:

像这样?

file.tell() 

返回文件的当前位置,如 stdio 的 ftell()。

http://docs.python.org/library/stdtypes.html#file-objects

不幸的是,tell() 不起作用,因为 OP 使用标准输入而不是文件。但是围绕它构建一个包装器来满足您的需要并不难。

class file_with_pos(object): 
    def __init__(self, fp): 
        self.fp = fp 
        self.pos = 0 
    def read(self, *args): 
        data = self.fp.read(*args) 
        self.pos += len(data) 
        return data 
    def tell(self): 
        return self.pos 

然后你可以用这个代替:

fp = file_with_pos(sys.stdin)