[Python] Learning Python : import exists

Discussão em 'Python' iniciado por Stack, Janeiro 3, 2025.

  1. Stack

    Stack Membro Participativo

    I just completed a Python 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?

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

    Continue reading...

Compartilhe esta Página