- 如果它存在,以读写模式打开文件;
- 如果不存在则创建它;
- 能够随时随地截断它。
EDIT:与截断我的意思是写直到一个位置,并丢弃该文件的剩余部分,如果存在的话
所有这些原子(具有单个open()
呼叫或模拟单个open()
呼叫)
没有一个单一的开放模式似乎也适用:
- R:显然是行不通的;
- r +:如果文件不存在则失败;
- w:重新创建文件,如果它存在;
- w +:重新创建文件,如果它存在;
- a:无法读取;
- a +:不能截断。
我试过的一些组合(rw,rw +,r + w等)似乎也不起作用。可能吗?
从Ruby的一些doc(适用于蟒太):
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.
所以你基本上是要覆盖一个文件并确保以前的内容不会停留在您停止写入的位置之下? – 2012-04-27 12:14:28
是的。 'file.truncate()'适用于这个目的,它在文件为“r +”,“w”,“w +”时起作用。但他们都有我上面列出的缺陷。 – ceztko 2012-04-27 12:21:21