擅长:python、mysql、java
<p>通过将路径作为字符串提供给<code>os.path.exists</code>,可以检查文件是否存在。但是,您所做的是提供一个文件句柄;因此<code>os.path.exists</code>返回<code>False</code>,即使文件存在</p>
<p>我甚至不建议检查是否存在。如果文件存在,一切都会正常,如果没有,您可以使用<code>try: except</code>捕获错误</p>
<p>另外,您没有关闭代码中的文件,这可能会导致问题。最好使用<code>with open(filename) as filehandle</code>语法打开它们,这样可以确保它们在最后被关闭</p>
<p>完整的示例代码可能如下所示:</p>
<pre><code>from sys import argv
import sys
script,fromf,tof=argv
try:
with open(fromf) as inf:
indata=inf.read()
with open(tof,'w') as outf:
outf.write(indata)
print("The task is accomplished.")
except:
print("Error!")
sys.exit()
</code></pre>