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

cez*_*tko 36 ruby python truncate

我想要:

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

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

所有这些原子(通过单个open()调用或模拟单个open()调用)

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

  • r:显然不起作用;
  • r +:如果文件不存在则失败;
  • w:重新创建文件(如果存在);
  • w +:如果存在则重新创建文件;
  • a:看不懂;
  • a +:不能截断.

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

来自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.
Run Code Online (Sandbox Code Playgroud)

cez*_*tko 30

根据OpenGroup的说法:

O_TRUNC

如果文件存在并且是常规文件,并且文件成功打开O_RDWR或O_WRONLY,则其长度将截断为0,并且模式和所有者不会更改.它对FIFO特殊文件或终端设备文件没有影响.它对其他文件类型的影响取决于实现.将O_TRUNC与O_RDONLY一起使用的结果是未定义的.

因此,当打开带有"w"或"w +"的文件时,可能会传递O_TRUNC.这给了"截断"一个不同的含义,而不是我想要的.

使用python,解决方案似乎在低级I/O中打开文件的os.open()功能.

以下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)
Run Code Online (Sandbox Code Playgroud)

有我想要的行为.您可以像这样使用它(实际上是我的用例):

# 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()
Run Code Online (Sandbox Code Playgroud)


ch3*_*3ka 14

嗯,只有这些模式,所有这些都有你列出的"缺陷".

你唯一的选择是包装open().为什么不这样的?(蟒蛇)

def touchopen(filename, *args, **kwargs):
    open(filename, "a").close() # "touch" file
    return open(filename, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

它的行为就像打开一样,如果你真的希望,你甚至可以将它重新打开().

保留所有open的功能,你甚至可以做到:

with touchopen("testfile", "r+") as testfile:
    do_stuff()
Run Code Online (Sandbox Code Playgroud)

您当然可以创建一个上下文管理器,它以+模式打开文件,将其读入内存,并拦截写入,以便通过在w模式下神奇地创建临时文件来处理截断,并在关闭时将该临时文件重命名为原始文件,但我觉得那太过分了.