我想要:
>如果文件存在,则以读写模式打开文件;
>如果它不存在则创建它;
>能够随时随地截断它.
编辑:使用truncate我的意思是写入一个位置并丢弃文件的剩余部分(如果存在)
所有这些原子(使用单个open()调用或模拟单个open()调用)
似乎没有单一的开放模态适用:
> r:显然不起作用;
> r:如果文件不存在则失败;
> w:重新创建文件(如果存在);
> w:重新创建文件(如果存在);
> a:看不懂;
> a:不能截断.
我试过的一些组合(rw,rw,r w等)似乎也不起作用.可能吗?
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()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。