簡體   English   中英

如何在python文件中獲取字節偏移

[英]How to get byte offset in a file in python

我正在使用hadoop和python進行反向索引。 我想知道如何在python中包含行/字的字節偏移量。 我需要這樣的東西

hello hello.txt@1124

我需要用於制作完整倒排索引的位置。 請幫忙。

像這樣?

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM