擅长:python、mysql、java
<p>如果需要再次打开该文件,例如由另一个进程读取此<a href="https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile" rel="nofollow noreferrer">might cause trouble on Windows OS</a>:</p>
<blockquote>
<p>Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).</p>
</blockquote>
<p>因此,一个安全的解决方案是<a href="https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory" rel="nofollow noreferrer">create a temporary directory</a>,然后在其中手动创建一个文件:</p>
<pre><code>import os.path
import tempfile
with tempfile.TemporaryDirectory() as td:
f_name = os.path.join(td, 'test')
with open(f_name, 'w') as fh:
fh.write('<content>')
# Now the file is written and closed and can be used for reading.
</code></pre>