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

eas*_*sid 1 python inverted-index

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

hello hello.txt@1124
Run Code Online (Sandbox Code Playgroud)

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

Wai*_*ung 8

像这样?

file.tell()
Run Code Online (Sandbox Code Playgroud)

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

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

不幸的是,由于OP使用的是stdin而不是文件,因此tell()不起作用.但要围绕它构建一个包装器来提供你需要的东西并不难.

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
Run Code Online (Sandbox Code Playgroud)

然后你可以用它代替:

fp = file_with_pos(sys.stdin)
Run Code Online (Sandbox Code Playgroud)