截断具有相对于目录/文件描述符的路径的文件? [英] Truncate file with a path relative to a directory/file descriptor?

查看:127
本文介绍了截断具有相对于目录/文件描述符的路径的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

os模块的许多方法(请参见文档)支持相对于文件描述符(dir_fd)的路径,例如unlink方法:

Many methods of the os module (see documentation) support paths relative to file descriptors (dir_fd), for example the unlink method:

os.unlink(path, *, dir_fd=None)

在某些情况下,我一直依赖此功能,尽管os的所有与文件相关的方法均不支持此功能.例如,truncate(直到并包括Python 3.7)缺少它:

I have been relying on this feature in a few cases, though it is not supported for all file-related methods of os. It's missing for truncate (until and including Python 3.7), for instance:

os.truncate(path, length)

如何解决此问题?

到目前为止,我最好的方法是显式打开文件:

My best idea so far is to explicitly open the file:

fd = os.open(path, flags = os.O_WRONLY | os.O_TRUNC, ... , dir_fd=dir_fd)
os.ftruncate(fd, length)
os.close(fd)

我想知道是否有更好的方法.

I was wondering whether there was a better method.

推荐答案

truncate没有dir_fd参数,因为没有truncateat系统调用.请参见此处进行讨论.

truncate does not have a dir_fd parameter, because there is no truncateat system call, which would be required for that. See discussion here.

正确且唯一可行的解​​决方案实际上是:

The proper and only feasible solution actually is:

def truncate(path, length, dir_fd = None):
    fd = os.open(path, flags = os.O_WRONLY, dir_fd = dir_fd)
    os.ftruncate(fd, length)
    os.close(fd)

与我最初的问题不同,打开文件时不得指定模式os.O_TRUNC.如果这样做的话,只要打开它,文件将被截断为零,这绝不是故意的.

Differing from my initial question, one MUST NOT specify mode os.O_TRUNC when opening the file. If one does that, the file will be truncated to zero by just opening it, which is by no means intended.

这篇关于截断具有相对于目录/文件描述符的路径的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆