samedi 25 mars 2017

Learning Python : import exists

I am learning Python and I am a super beginner! I just completed an exercise and wanted to create variations of it. My question is, when using the IF/ELSE statement how can I avoid using "out_file = open(to_file,'w') out_file.write(indata)" twice. Thanks in advance!

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()

Aucun commentaire:

Enregistrer un commentaire