<p>根据<a href="http://pubs.opengroup.org/onlinepubs/7908799/xsh/open.html" rel="noreferrer">OpenGroup</a>:</p>
<blockquote>
<p>O_TRUNC</p>
<p>If the file exists and is a regular file, and the file is successfully
opened O_RDWR or O_WRONLY, its length is truncated to 0 and the mode
and owner are unchanged. It will have no effect on FIFO special files
or terminal device files. Its effect on other file types is
implementation-dependent. The result of using O_TRUNC with O_RDONLY is
undefined.</p>
</blockquote>
<p>所以,打开“w”或“w+”文件时可能会传递O_TRUNC。这给了“截断”一个不同的含义,不是我想要的。</p>
<p>使用python,解决方案似乎是使用<code>os.open()</code>函数以低级别I/O打开文件。</p>
<p>以下python函数:</p>
<pre><code>def touchopen(filename, *args, **kwargs):
# Open the file in R/W and create if it doesn't exist. *Don't* pass O_TRUNC
fd = os.open(filename, os.O_RDWR | os.O_CREAT)
# Encapsulate the low-level file descriptor in a python file object
return os.fdopen(fd, *args, **kwargs)
</code></pre>
<p>有我想要的行为。你可以这样使用它(实际上这是我的用例):</p>
<pre><code># Open an existing file or create if it doesn't exist
with touchopen("./tool.run", "r+") as doing_fd:
# Acquire a non-blocking exclusive lock
fcntl.lockf(doing_fd, fcntl.LOCK_EX)
# Read a previous value if present
previous_value = doing_fd.read()
print previous_value
# Write the new value and truncate
doing_fd.seek(0)
doing_fd.write("new value")
doing_fd.truncate()
</code></pre>