【发布时间】:2012-04-27 11:27:13
【问题描述】:
我想:
- 如果文件存在,则以读写模式打开文件;
- 如果不存在则创建它;
- 能够随时随地截断它。
编辑:截断我的意思是写到一个位置并丢弃文件的剩余部分(如果存在)
所有这些都是原子的(使用单个 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.
【问题讨论】:
-
所以您实际上是想覆盖一个文件并确保之前的内容不会停留在您停止写入的点以下?
-
是的。
file.truncate()用于此目的,并且在文件为“r+”、“w”、“w+”时有效。但它们都有我上面列出的缺陷。