gpt4 book ai didi

python - 如何打开(读写)或创建允许截断的文件?

转载 作者:IT老高 更新时间:2023-10-28 21:49:48 25 4
gpt4 key购买 nike

我想:

  • 如果文件存在,则以读写模式打开文件;
  • 如果不存在就创建它;
  • 能够随时随地截断它。

编辑:截断我的意思是写到一个位置并丢弃文件的剩余部分(如果存在)

所有这些都是原子的(使用单个 open() 调用或模拟单个 open() 调用)

似乎没有单一的开放模式适用:

  • r : 显然不行;
  • r+ : 如果文件不存在则失败;
  • w:如果存在则重新创建文件;
  • w+:如果文件存在则重新创建;
  • a:无法阅读;
  • a+:不能截断。

我尝试过的一些组合(rw、rw+、r+w 等)似乎也不起作用。有可能吗?

一些 doc来自 Ruby(也适用于 python):

r
Read-only mode. The file pointer is placed at the beginning of the file.
This is the default mode.

r+
Read-write mode. The file pointer will be at the beginning of the file.

w
Write-only mode. Overwrites the file if the file exists. If the file
does not exist, creates a new file for writing.

w+
Read-write mode. Overwrites the existing file if the file exists. If the
file does not exist, creates a new file for reading and writing.

a
Write-only mode. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist,
it creates a new file for writing.

a+
Read and write mode. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it
creates a new file for reading and writing.

最佳答案

根据OpenGroup :

O_TRUNC

If the file exists and is a regular file, and the file is successfully opened O_RDWR or O_WRONLY, its length is truncated to 0 and the mode and owner are unchanged. It will have no effect on FIFO special files or terminal device files. Its effect on other file types is implementation-dependent. The result of using O_TRUNC with O_RDONLY is undefined.

所以,当使用“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 exist
with 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()

关于python - 如何打开(读写)或创建允许截断的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10349781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com