我想要:
- 如果文件存在,则以读写模式打开文件;
- 如果它不存在,则创建它;
- 能够随时随地截断它。
编辑:截断我的意思是写到一个位置并丢弃文件的剩余部分(如果存在)
所有这些都是原子的(使用单个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.