The preferred method of file i/o is to use the with
keyword. This will ensure the file handle is closed once the reading or writing has been completed.
with open('myfile.txt') as in_file:
content = in_file.read()
print(content)
or, to handle closing the file manually, you can forgo with
and simply call close
yourself:
in_file = open('myfile.txt', 'r')
content = in_file.read()
print(content)
in_file.close()
Keep in mind that without using a with
statement, you might accidentally keep the file open in case an unexpected exception arises like so:
in_file = open('myfile.txt', 'r')
raise Exception("oops")
in_file.close() # This will never be called