0

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()
3
  • 3
    You are not going to run out of lines, there is no reason to reduce 2 lines to 1 here. That said, the modern idiomatic way is with open(from_file) as f: indata = f.read() Commented Feb 4, 2019 at 12:21
  • I'm following tutorials and I would agree, it's actually easier to understand if you separate out the lines for the open() function, then call a method like read() or write() on a separate line. Makes the program more structured and readable. Thanks for your comment. Commented Feb 4, 2019 at 12:24
  • What happened when you tried? Commented Feb 4, 2019 at 12:34

2 Answers 2

2

You can use the "with open"

One way of doing it is like below:

with open(from_file) as in_file, open(to_file, 'w') as out_file:
    indata = in_file.read()
    out_file.write(indata)

Apart from combining the lines, one benefit of this is that, you don't have explicitly close the files, they will be automatically closed when you exit the with block

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

Comments

0

Your script file could be more pythonic using with, also you can avoid dumping all file into memory using generators (a file object is a generator itself):

if __name__ == "__main__":
  from sys import argv
  from os.path import exists
  script, from_file, to_file = argv
  with open(from_file, "r") as inf, open(to_file, "w") as outf:
    outf.writelines(inf)

1 Comment

if their actual aim is to copy files they would use shutil.copyfile but you would imagine their example is a placeholder for more complex code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.