Open In App

Python open() Function

Last Updated : 29 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 thegeeksforgeeks.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

How to open multiple files using "with open" in Python?
Python has various highly useful methods for working with file-like objects, like the with feature. But what if we need to open several files in this manner? You wouldn't exactly be "clean" if you had a number of nested open statements. In this article, we will demonstrate how to open multiple files in Python using the with open statement. What is
2 min read
Difference between modes a, a+, w, w+, and r+ in built-in open function?
Understanding the file modes in Python's open() function is essential for working with files effectively. Depending on your needs, you can choose between 'a', 'a+', 'w', 'w+', and 'r+' modes to read, write, or append data to files while handling files. In this article, we'll explore these modes and their use cases. Difference between modes a, a+, w
4 min read
Python PIL | Image.open() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. PIL.Image.open() Opens
2 min read
Python | sympy.sets.open() method
With the help of sympy.sets.open() method, we can make a set of values by setting interval values like right open or left open that means a set has right open bracket and left open brackets by using sympy.sets.open() method. Syntax : sympy.sets.open(val1, val2) Return : Return set of values with right and left open set. Example #1 : In this example
1 min read
Open a new Window with a button in Python-Tkinter
Python provides a variety of GUI (Graphic User Interface) such as PyQt, Tkinter, Kivy and soon. Among them, tkinter is the most commonly used GUI module in Python since it is simple and easy to learn and implement as well. The word Tkinter comes from the tk interface. The tkinter module is available in Python standard library.Note: For more informa
3 min read
How to open and close a file in Python
There might arise a situation where one needs to interact with external files with Python. Python provides inbuilt functions for creating, writing, and reading files. In this article, we will be discussing how to open an external file and close the same using Python. Opening a file in Python There are two types of files that can be handled in Pytho
4 min read
Python - Convert Tick-by-Tick data into OHLC (Open-High-Low-Close) Data
In this post, we'll explore a Python pandas package feature. We frequently find queries about converting tick-by-tick data to OHLC (Open, High, Low and Close). Using pandas kit this can be done with minimum effort. The OHLC data is used over a unit of time (1 day, 1 hour etc.) to perform a technical analysis of price movement. The First Step: The f
2 min read
Open computer drives like C, D or E using Python
Have you ever wondered that you can open your drives by just typing C, D or E and then that drives are open.This can be possible by using Python. So, for performing this task this we are using os.startfile() method of OS library. This Method start a file with its associated program. Syntax: os.startfile(file_name) Return: None. Now let's see the co
1 min read
Open Applications using Python
In this article, we are going to CLI application using Python3. We are going to include the below applications in the menu: GOOGLE CHROMEMS EDGEMS WORDTELEGRAMopelnWHATSAPPNOTEPAD++and all the applications installed...Module Needed AppOpener: It is the python library which helps in opening/closing any application without knowing it's absolute path.
5 min read
How to open two files together in Python?
Prerequisites: Reading and Writing text files in Python Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files. An arbitrary number of files can be opened with the open() method supported in Python 2.7 ve
2 min read
Practice Tags :