代码之家  ›  专栏  ›  技术社区  ›  easysid

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

  •  1
  • easysid  · 技术社区  · 14 年前

    我需要这样的东西

    hello hello.txt@1124
    

    请帮忙。

    1 回复  |  直到 14 年前
        1
  •  10
  •   Wai Yip Tung    14 年前

    这样地?

    file.tell()
    

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

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

    不幸的是tell()不起作用,因为OP使用的是stdin而不是文件。但是在它周围构建一个包装器来满足您的需求并不难。

    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)
    
    推荐文章