Python open() is “used to open the file (if possible) and returns the corresponding file object.” If a file is not found, then it raises the FileNotFoundError exception.
Syntax
open(file, mode)
Parameters
Parameter | Description |
---|---|
file | The path and name of a file. |
mode | The sting, define which mode you want to open the file in:
“r” – Read – Default value. It opens the file for reading and err if it does not exist. “a” – Append – Opens the file for appending and creates the file if it does not exist. “w” – Write – Opens the file for writing and creates a file if it does not exist. “x” – Create – Creates a specified file and returns an error if the file exists. Also, you determine if a file should be handled in binary or text mode. “t” – Text – Default value. Text mode. “b” – Binary – Binary mode (e,.g. images). |
Return value
The open() function returns a file object which can be used to read, write, and modify the file.
Example 1: How to Use open() function
To open a file in Python, use the open() function. The open() function accepts files and various modes that can help you while opening a file.
f = open("app.txt")
print(f)
Output
<_io.TextIOWrapper name='app.txt' mode='r' encoding='UTF-8'>
Since the mode is omitted, the file is opened in ‘r’ mode; it opens for reading.
Example 2: Passing the “r” mode
Let’s pass the ‘r’ mode as a parameter and see the output.
f = open("app.txt", 'r')
print(f)
It will give us the same output as above.
Python has a platform-dependent encoding system. Hence, specifying an encoding type is recommended if working in text mode.
f = open("path_to_file", mode = 'r', encoding='utf-8')
Example 3: Passing the “w” mode
Let’s pass the ‘w’ mode. The ‘w‘ stands for writing mode.
f = open("app.txt", 'w')
print(f)
Output
<_io.TextIOWrapper name='app.txt' mode='w' encoding='UTF-8'>
Example 4: Passing the “a” mode
Let’s pass the ‘a’ mode. The ‘a’ stands for append mode.
f = open("app.txt", 'a')
print(f)
Output
<_io.TextIOWrapper name='app.txt' mode='a' encoding='UTF-8'>
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.