根据OpenGroup:
O_TRUNC
如果文件存在并且是常规文件,并且文件已成功打开O_RDWR或O_WRONLY,则其长度将被截断为0,并且模式和所有者不变。它对FIFO特殊文件或终端设备文件没有影响。它对其他文件类型的影响取决于实现。O_TRUNC和O_RDONLY一起使用的结果是不确定的。
因此,用“ w”或“ w +”打开文件时可能会传递O_TRUNC。这给“截断”带来了不同的含义,而不是我想要的含义。
使用python,该解决方案似乎可以通过
os.open()功能在低级I / O上打开文件。
以下python函数:
def touchopen(filename, *args, **kwargs): # Open the file in R/W and create if it doesn't exist. *Don't* pass O_TRUNC fd = os.open(filename, os.O_RDWR | os.O_CREAT) # Encapsulate the low-level file descriptor in a python file object return os.fdopen(fd, *args, **kwargs)
有我想要的行为。您可以像这样使用它(实际上是我的用例):
# Open an existing file or create if it doesn't existwith touchopen("./tool.run", "r+") as doing_fd: # Acquire a non-blocking exclusive lock fcntl.lockf(doing_fd, fcntl.LOCK_EX) # Read a previous value if present previous_value = doing_fd.read() print previous_value # Write the new value and truncate doing_fd.seek(0) doing_fd.write("new value") doing_fd.truncate()


