If statement 学习Python:存在导入

If statement 学习Python:存在导入,if-statement,If Statement,我正在学习Python,我是一个超级初学者! 我刚刚完成了一个练习,并想创建它的变体。 我的问题是,当使用IF/ELSE语句时,如何避免使用 “out_file=open(to_file,'w')out_file.write(indata)”两次。 提前谢谢 from sys import argv from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s" % (fro

我正在学习Python,我是一个超级初学者! 我刚刚完成了一个练习,并想创建它的变体。 我的问题是,当使用IF/ELSE语句时,如何避免使用 “out_file=open(to_file,'w')out_file.write(indata)”两次。 提前谢谢

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

in_file = open(from_file)
indata = in_file.read()

print "The input file is %d bytes long" % len(indata)

if exists(to_file):
    print "File already exists, override?"
    raw_input()
else:
    out_file = open(to_file,'w')
    out_file.write(indata)

out_file = open(to_file,'w')
out_file.write(indata)

print"Done."

out_file.close()
in_file.close()

<> P>目前你的脚本并没有真正考虑用户的输入是否重写,而不管它们的输入是否重写。看起来你想考虑他们的输入,所以我会推荐一些类似的东西:

proceed = False
if exists(to_file):
    print "File already exists, override?"
    ans = raw_input("y/n: ")
    if ans == "y":
        proceed = True
else:
    proceed = True

if proceed:
    out_file = open(to_file,'w')
    out_file.write(indata)

此外,如果来自_文件的
不存在,您可能需要执行一些错误处理,因为在这种情况下,调用
open()
将引发
IOError
——请参见

我想您已经偶然发现了存在的主要原因之一:)正如我所说,我刚刚开始深入编码世界。所以,请给我举个例子,这样我就可以学习了!;)我喜欢使用
procedure
将两个嵌套条件转换为一个用于写入文件的标志。我也喜欢这个答案,只有当用户要写入时,才会打开输出文件。并呼吁需要处理更多的错误-非常好。非常感谢。如果文件已经存在,我只想考虑用户输入。