如何在python中获取文件中的字节偏移 [英] How to get byte offset in a file in python
本文介绍了如何在python中获取文件中的字节偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用hadoop和python进行反向索引. 我想知道如何在python中包含行/字的字节偏移量. 我需要这样的东西
I am making a inverted index using hadoop and python. I want to know how can I include the byte offset of a line/word in python. I need something like this
hello hello.txt@1124
我需要用于制作完整倒排索引的位置. 请帮忙.
I need the locations for making a full inverted index. Please help.
推荐答案
喜欢吗?
file.tell()
返回文件的当前位置,例如stdio的ftell().
Return the file’s current position, like stdio's ftell().
http://docs.python.org/library/stdtypes.html#文件对象
不幸的是,tell()无法运行,因为OP使用的是stdin而不是文件.但是,围绕它构建包装以提供所需的东西并不难.
Unfortunately tell() does not function since OP is using stdin instead of a file. But it is not hard to build a wrapper around it to give what you need.
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)
这篇关于如何在python中获取文件中的字节偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文