The Python open() function is used to open internally stored files. It returns the contents of the file as Python objects.
Python open() Function Syntax
The open() function in Python has the following syntax:
Syntax: open(file_name, mode)
Parameters:
file_name: This parameter as the name suggests, is the name of the file that we want to open.
mode: This parameter is a string that is used to specify the mode in which the file is to be opened. The following strings can be used to activate a specific mode:
- "r": This string is used to read(only) the file. It is passed as default if no parameter is supplied and returns an error if no such file exists.
- "w": This string is used for writing on/over the file. If the file with the supplied name doesn't exist, it creates one for you.
- "a": This string is used to add(append) content to an existing file. If no such file exists, it creates one for you.
- "x": This string is used to create a specific file.
- "b": This string is used when the user wants to handle the file in binary mode. This is generally used to handle image files.
- "t": This string is used to handle files in text mode. By default, the open() function uses the text mode.
How to open a file in Python?
In Python, we can open a file by using the open() function already provided to us by Python. By using the open() function, we can open a file in the current directory as well as a file located in a specified location with the help of its path. In this example, we are opening a file "gfg.txt" located in the current directory and "gfg1.txt" located in a specified location.
Python3
# opens gfg text file of the current directory
f = open("gfg.txt")
# specifying the full path
f = open("C:/HP/Desktop/gfg1.txt")
open() Function in Python Examples
Let us see a few examples of the Python open() function.
Creating a Text File
The open() function in Python can be used to create a file. Here we will be creating a text file named "geeksforgeeks.txt".
Python3
created_file = open("geeksforgeeks.txt","x")
# Check the file
print(open("geeksforgeeks.txt","r").read() == False)
Output:
False
Reading and Writing the file
Here we will write the following string to the "geeksforgeeks.txt" file that we just created and read the same file again.
Geeksforgeeks is best for DSA
The below code can be used for the same:
Python3
my_file = open("geeksforgeeks.txt", "w")
my_file.write("Geeksforgeeks is best for DSA")
my_file.close()
#let's read the contents of the file now
my_file = open("geeksforgeeks.txt","r")
print(my_file.read())
Output:
Geeksforgeeks is best for DSA
Appending content to the file
Here we will append the following text to the "geeksforgeeks.txt" file and again read the same.
..>>Visit geeksforgeeks.org for more!!<<..
Python3
my_file = open("geeksforgeeks.txt","a")
my_file.write("..>>Visit geeksforgeeks.org for more!!<<..")
my_file.close()
# reading the file
my_file = open("geeksforgeeks.txt","r")
print(my_file.read())
Output:
Geeksforgeeks is best for DSA..>>Visit geeksforgeeks.org for more!!<<..
Note: The difference between "w" and "a" is that one overrides over the existing content whereas the latter adds content to the existing file keeping the content intact.
Similar Reads
Python len() Function The len() function in Python is used to get the number of items in an object. It is most commonly used with strings, lists, tuples, dictionaries and other iterable or container types. It returns an integer value representing the length or the number of elements. Example:Pythons = "GeeksforGeeks" # G
2 min read
Python print() function The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
2 min read
Python int() Function The Python int() function converts a given object to an integer or converts a decimal (floating-point) number to its integer part by truncating the fractional part.Example:In this example, we passed a string as an argument to the int() function and printed it.Pythonage = "21" print("age =", int(age)
3 min read
Python map() function The map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator). Let's start with a simple example of using map() to convert a list of strings into a list of integers.Pythons = ['1', '2', '3', '4'] res = map(
4 min read
pow() Function - Python pow() function in Python is a built-in tool that calculates one number raised to the power of another. It also has an optional third part that gives the remainder when dividing the result. Example:Pythonprint(pow(3,2))Output9 Explanation: pow(3, 2) calculates 32 = 9, where the base is positive and t
2 min read