Python Open is an in-built function of Python library which does exactly as its name suggests. This function opens a file and returns its file object.
Syntax of the Python open ( )
Open(‘file’, ‘open_mode’)
The syntax of the Python open function is simple. This function takes two string type parameters, which are –
File: Here you have to specify the name of the file. You can do so in two ways –
- Specify only the name of the file (demoFile.txt) or
- Write the name of the file with its location path (C:\Documents\demoFile.txt)
Let’s say you go with the first option and specify only the name of the file. Then the Python interpreter function first looks for the file in the directory of your current project. If it finds the file there, then it will open it otherwise it will create the file in your project directory.
And, if you go with the second option then the interpreter will look for the file in the specified directory. If it finds the file there then it will open it otherwise it will create the file.
Open Mode
Open modes are just characters which indicate a special meaning. There are total of seven open modes available which you can use in Python open function. These seven open modes are –
‘r’Â Â Â Â Â Â Â Â open the file in read-only mode (default)
‘w’Â Â Â Â Â Â Â open the file in write-only mode, truncating the file first
‘x’Â Â Â Â Â Â Â Â open for exclusive creation, failing if the file already exists
‘a’Â Â Â Â Â Â Â Â open for writing, appending to the end of the file if it exists
‘b’Â Â Â Â Â Â Â Â binary mode
‘t’Â Â Â Â Â Â Â Â text mode (default)
‘+’Â Â Â Â Â Â Â open a disk file for updating (reading and writing)
Always remember, if you open the file in write-only mode (‘w’) then the function will delete all the pre-existed data of the file. Be careful there. If you want to add data at the end of the file without deleting the pre-existed data, then use append mode (‘a’).
What does Python open function return?
Python open function returns a file object which points towards the file which you have specified in the function call. Using this file object, you can read, write or append your file.
A file object is an object which lets you read, write, and append data into a file.
Now that you have learnt all about Python Open Function. It’s time for you to see it in action. I have demonstrated how to open a file using Python open function in Python Tutorial 20. Click here to check that out.