In this article, we are going to learn Python’s most important function that is an open() function. open() function in python is used to open a file and returns a object.
You can learn all about Python open function in our file handling tutorial.
Table of Contents
Python open function
The Python open function is a Python built-in function that is used to open the file and returns the file object. Using file objects you can perform various operations on the file.
Syntax
The syntax of Python open function is:-
open(filename, mode)
Return Value
The return value of open function in Python is file object.
Parameter Value
open function in python supports two parameters.
- filename:- The path and name of the file.
- mode:- A string, you want to open a file.
“r”:- Read mode, Default value
“w”:- Writing, Open a file for writing.
“a”:- Append, Open a file for writing.
“x”:- Create the specified file.
“t”:- Text mode, Default value.
“b”:- Binary, Binary mode.
Python open() function example
Here we will take some examples to understand open function in Python.
Example 1:
In this example, we will read content from the myfile.txt file.
We have a file myfile.txt in the current working directory that contains small contents.
myfile.txt
Welcome to Programming Funda online Python tutorial.
Now will read content from the myfile.txt using Python open function.
file = open('myfile.txt', 'r')
print(file.read())
Output
Welcome to Programming Funda online Python tutorial.
Example 2:
In this example we will write a file.
file = open('myfile.txt', 'w')
file.write("This is my file")
Conclusion
In this tutorial, you have learned about Python open function along with examples. You can learn all about Python open function in our file handling tutorial.
if you like this article, please share and keep visiting for further Python built-in functions tutorials.
Python built-in functions tutorials
For more information:- Click Here