擅长:python、mysql、java
<p>您已经<code>open</code>该文件了。如果文件不存在,就会出现异常。所以你的测试是无用的(正如Reut解释的那样是错误的)</p>
<p>此外,“覆盖前检查文件是否存在”功能不起作用:</p>
<pre><code>outf=open(tof,'w')
if exists(str(outf))==True:
print("Error! Output file exists.")
sys.exit()
else:
outf.write(indata)
print("The task is accomplished.")
</code></pre>
<p>您打开文件进行写入,因此无需检查文件是否存在,测试是否错误(出于相同的原因),但即使它是正确的,也会与您想要的功能相反</p>
<p>您希望避免覆盖现有文件,所以在截短它之前测试<em>,否则就太晚了,您总是会出错退出</p>
<p>固定代码:</p>
<pre><code>if exists(tof):
print("Error! Output file exists.")
sys.exit()
outf=open(tof,'w')
</code></pre>