What does open() function do in Python?

PythonServer Side ProgrammingProgramming

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

f = open('my_file', 'r+')
my_file_data = f.read()

 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 writethe file, pass in r+

– If you want to overwrite thefile, pass in w

– If you want to append to thefile, 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 21-Dec-2017 17:50:22