擅长:python、mysql、java
<p>以下方法的优点是文件在块的末尾被正确关闭,即使在过程中引发异常。它相当于<code>try-finally</code>,但要短得多。</p>
<pre><code>with open("file.dat","a+") as f:
f.write(...)
...
</code></pre>
<blockquote>
<p><strong>a+</strong> Opens a file for both appending and reading. 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. -<a href="http://www.tutorialspoint.com/python/python_files_io.htm" rel="noreferrer">Python file modes</a></p>
</blockquote>
<p><a href="http://www.tutorialspoint.com/python/file_seek.htm" rel="noreferrer">seek() method</a>设置文件的当前位置。</p>
<pre><code>f.seek(pos [, (0|1|2)])
pos .. position of the r/w pointer
[] .. optionally
() .. one of ->
0 .. absolute position
1 .. relative position to current
2 .. relative position from end
</code></pre>
<blockquote>
<p>Only "rwab+" characters are allowed; there must be exactly one of "rwa" - see Stack Overflow question <em><a href="https://stackoverflow.com/a/656289/985454">Python file modes detail</a></em>.</p>
</blockquote>