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

我想要:

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

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

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

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

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

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

来自Ruby的一些doc(也适用于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()
上一篇:Mysql-删除数据表-三种方式详解


下一篇:mysql之drop、truncate和delete的区别