在Python中获取文件描述符的位置

4 投票
1 回答
3464 浏览
提问于 2025-04-19 14:23

假设我有一个原始的数字文件描述符,我需要根据它获取当前在文件中的位置。

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()只返回了文件中的第一个位置,并且在循环中没有更新。

有没有办法根据文件描述符获取当前实时的文件位置呢?

1 个回答

2

所以,答案看起来很简单。我需要使用 os.lseek 这个函数,并且加上 SEEK_CUR 这个标志:

import os
print(os.lseek(fd, 0, os.SEEK_CUR))

我不知道这是不是唯一的方法,但至少这个方法运行得很好。

解释一下: 在文件描述符上使用 ftell?

撰写回答