在python中,程序将一个文件的内容复制到另一个文件的输出错误

2024-06-25 23:13:49 发布

您现在位置: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存在。。。但它仍然显示“错误!“输入文件不存在”


Tags: 文件fromimporttxtos错误existssys
3条回答

通过将路径作为字符串提供给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')

os.path.exists需要路径(字符串),而不是file对象

您应该使用fromf作为参数:

if exists(fromf): # no need for " == True"
    # ...

相关问题 更多 >