[英]Getting wrong output for a program to copy the contents of one file to another in python
即使文件存在,我也会得到错误的输出。 以下是代码...
from sys import argv
from os.path import exists
import sys
import os
script,fromf,tof=argv
inf=open(fromf)
if exists(str(inf))==True:
indata=inf.read()
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.")
else:
print("Error! Input file doesn't exists.")
我在通过以下论点...。
python3 file.py aaa.txt bbb.txt
文件aaa.txt存在...但仍然显示“错误!输入文件不存在”
os.path.exists
需要路径(字符串),而不是file
对象。
您应该使用fromf
作为参数:
if exists(fromf): # no need for " == True"
# ...
您可以通过将路径作为字符串提供给os.path.exists
来检查文件是否存在。 但是,您正在执行的操作是提供文件句柄。 因此,即使文件存在, os.path.exists
返回False
。
我不会建议甚至检查是否存在。 如果文件存在,一切都会好的,否则,您可以使用try: except
捕获错误。
另外,您不要关闭代码中的文件,这可能会导致问题。 最好使用with open(filename) as filehandle
语法来打开它们,以确保它们将在最后关闭。
完整的示例代码如下所示:
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()
您已经open
文件。 如果该文件不存在,则会出现异常。 因此,您的测试没有用(正如Reut所说的那样是错误的)。
此外,您的“在覆盖前检查文件是否存在”功能不起作用:
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.")
您打开文件进行写入,因此无需检查文件是否存在,并且测试是错误的(出于同样的原因),但是即使正确,它也会执行您想要的功能。
您希望避免覆盖现有文件,因此请在截断之前进行测试,否则为时已晚,并且始终会出错退出!
固定代码:
if exists(tof):
print("Error! Output file exists.")
sys.exit()
outf=open(tof,'w')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.