# How to safely open/close files in Python?

PythonServer Side ProgrammingProgramming

open() opens a file. You can use it like:

f = open('my_file', 'r+')
f.close()

The above code opens 'my_file' in read mode then stores the data it reads from my_file in my_file_data and closes the file. The first argument of open is the name of the file and second one is the open mode. It determines how the file gets opened.

### For example

– If you want to read the file, pass in r
– If you want to read and write the file, pass in r+
– If you want to overwrite the file, pass in w
– If you want to append to the file, pass in a

When you open a file, the operating system gives a file handle to read/write the file. You need to close it once you are done using the file. If your program encounters an error and doesn't call f.close(), you didn't release the file. To make sure it doesn't happen, you can use with open(...) as f syntax as it automatically closes files regardless of whether an error was encountered:

with open('my_file', 'r+') as f:
my_file_data = f.read()
Published on 27-Dec-2017 08:04:04