擅长:python、mysql、java
<p>您遇到了范围问题;文件<code>tmp</code>只存在于创建它的<code>with</code>语句的范围内。此外,如果您想稍后在初始<code>with</code>之外访问该文件,则需要使用<code>NamedTemporaryFile</code>(这使操作系统能够访问该文件)。另外,我不知道你为什么要附加到一个临时文件。。。因为在你实例化它之前它是不存在的。</p>
<p>试试这个:</p>
<pre><code>import tempfile
tmp = tempfile.NamedTemporaryFile()
# Open the file for writing.
with open(tmp.name, 'w') as f:
f.write(stuff) # where `stuff` is, y'know... stuff to write (a string)
...
# Open the file for reading.
with open(tmp.name) as f:
for line in f:
... # more things here
</code></pre>