<p>我想:</p>
<ul>
<li>以读写模式打开文件(如果存在)</li>
<li>如果它不存在就创造它</li>
<li>可以随时随地截短它。</li>
</ul>
<p><strong>编辑</strong>:对于truncate,我的意思是写到某个位置,并丢弃文件的剩余部分(如果存在)</p>
<p>所有这些都是原子式的(使用单个<code>open()</code>调用或模拟单个<code>open()</code>调用)</p>
<p>似乎没有单一的开放模式适用:</p>
<ul>
<li>r:显然不行</li>
<li>r+:如果文件不存在,则失败</li>
<li>w: 如果文件存在,请重新创建该文件</li>
<li>w+:如果文件存在,则重新创建该文件</li>
<li>a: 不能阅读</li>
<li>a+:无法截断。</li>
</ul>
<p>我尝试的一些组合(r w、rw+、r+w等)似乎也不起作用。有可能吗?</p>
<p>Ruby中的一些<a href="http://www.tutorialspoint.com/ruby/ruby_input_output.htm">doc</a>(也适用于python):</p>
<pre><code>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 <a href="https://www.cnpython.com/list/append" class="inner-link">append</a> 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.
</code></pre>