0

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()
2
  • I think you've stumbled upon one of the main reasons why functions exist :) Commented Mar 25, 2017 at 16:56
  • As I said, I just started to dive into the world of coding. So please, give me an example so I can learn! ;) Commented Mar 27, 2017 at 16:38

1 Answer 1

1

Currently your script doesn't genuinely consider the user's input for whether to overwrite, and you overwrite regardless of their input. It looks like you want to consider their input, so I would recommend something like:

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)

Also, you'll probably want to do some error handling if the from_file doesn't exist, as in that circumstance the call to open() will raise an IOError -- see https://docs.python.org/2/library/functions.html#open

Sign up to request clarification or add additional context in comments.

2 Comments

I like the use of proceed turn 2 nested conditions into one flag for writing the file. I also like that this answer opens the output file only if the user is going to write to it. And calling out the need to handle more errors - very nice.
Thank you very much. I want to consider user input only if file already exists.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.