In the following Python script, I'm utilising the open() function to create a file object and then reading from it using the read() method. It's a simple script that will copy one file to another.
I have 2 questions:
1) Can the lines where we assign in_file and indata be combined? I understand that we create a file object, then we read from it - however can this be done in a single line of code? I'm guessing for example on option we can possibly chain the open() function and read() method together?
2) Can the two lines of code that assign the out_file variable be refactored in a similar fashion? We again create a separate file object using open(), then write to it using the write() method.
Please keep answers as simple as possible and explain what is happening in the code.
from sys import argv
from os.path import exists
script, from_file, to_file = argv
# we could combine these two lines of code into one line, how?
in_file = open(from_file)
indata = in_file.read()
# could these two lines be combined in a similar way?
out_file = open(to_file, 'w')
out_file.write(indata)
in_file.close()
out_file.close()
with open(from_file) as f: indata = f.read()