在Python中获取文件描述符的位置
发布时间:2020-12-20 13:44:35 所属栏目:Python 来源:网络整理
导读:说,我有一个原始的数字文件描述符,我需要根据它获取文件中的当前位置. import os,psutil# some code that works with filelp = lib.open('/path/to/file')p = psutil.Process(os.getpid())fd = p.get_open_files()[0].fd # intwhile True: buf = lp.read() i
说,我有一个原始的数字文件描述符,我需要根据它获取文件中的当前位置.
import os,psutil # some code that works with file lp = lib.open('/path/to/file') p = psutil.Process(os.getpid()) fd = p.get_open_files()[0].fd # int while True: buf = lp.read() if buf is None: break device.write(buf) print tell(fd) # how to find where we are now in the file? 在下面的代码中,lib是一个编译库,它不提供对文件对象的访问.在循环中,我使用嵌入式方法read,它返回处理过的数据.数据及其长度与文件位置无关,因此无法以数学方式计算偏移量. 我尝试使用fdopen,如fd = fdopen(p.get_open_files()[0] .fd),但print fd.tell()仅返回文件中的第一个位置,该位置未在循环中更新. 有没有办法根据文件描述符获取文件中的当前实时位置? 解决方法
所以,答案似乎很容易.我不得不使用带有SEEK_CUR标志的
os.lseek :
print os.lseek(fd,os.SEEK_CUR) 我不知道这是否是唯一的方法,但至少它工作正常. 解释:ftell on a file descriptor? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |