As a complete beginner to programming, I am trying to understand the basic concepts of opening and closing files. One exercise I am doing is creating a script that allows me
The answers so far are absolutely correct when working in python. You should use the with open()
context manager. It's a great built-in feature, and helps shortcut a common programming task (opening and closing a file).
However, since you are a beginner and won't have access to context managers and automated reference counting for the entirety of your career, I'll address the question from a general programming stance.
The first version of your code is perfectly fine. You open a file, save the reference, read from the file, then close it. This is how a lot of code is written when the language doesn't provide a shortcut for the task. The only thing I would improve is to move close()
to where you are opening and reading the file. Once you open and read the file, you have the contents in memory and no longer need the file to be open.
in_file = open(from_file)
indata = in_file.read()
out_file.close()
out_file = open(to_file, 'w')
out_file.write(indata)
in_file.close()