我想:
- 以读写模式打开文件(如果存在);
- 如果它不存在,就创造它;
- 可以随时随地截断它.
EDIT:使用truncate,我的意思是写到某个位置,并丢弃文件的剩余部分(如果存在)
所有这些都是原子性的(通过单个open()
次调用或模拟单个open()
次调用)
似乎没有单一的开放模式适用:
- r:显然不行;
- r+:如果文件不存在,则失败;
- w:重新创建文件(如果存在);
- w+:重新创建文件(如果存在);
- 答:不识字;
- a+:无法截断.
我try 过的一些组合(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.