As a data scientist working on a project for one of my clients, I often need to read data from various file formats like CSV, TEXT, JSON, etc. In this tutorial, I will explain how to open a file in Python. Let us learn the basics of opening files, different modes for opening files, and provide examples using common file types.
Open a File in Python
Python provides a built-in function open() that allows you to open files. The open() function takes two arguments: the file name (including the path if necessary) and the mode in which you want to open the file.
Here’s the basic syntax:
file_object = open("file_name.txt", "mode")Let’s break this down with an example. Suppose you have a file named “customers.txt” in the same directory as your Python script. You can open it like this:
customer_file = open("customers.txt", "r")In this example, “r” stands for read mode, which is the default mode if you don’t specify one.
Read How to Save a Python Dictionary as a JSON File?
Modes to Open a File
Python offers several modes for opening files:
- “r” (Read Mode): This is the default mode. It opens the file for reading only.
- “w” (Write Mode): Opens the file for writing. If the file already exists, it will be overwritten. If it doesn’t exist, a new file will be created.
- “a” (Append Mode): Opens the file for appending data. If the file doesn’t exist, a new file will be created.
- “x” (Exclusive Creation Mode): Creates a new file, but raises an error if the file already exists.
You can also add “b” to the mode to open the file in binary mode, which is useful for non-text files like images or executable files.
Check out How to Get File Size in Python?
Work with Different File Types
Let us see how opening a file works with different file types.
Text Files (.txt)
Text files are the most common file type. Here’s an example of how to open and read a text file:
with open("employees.txt", "r") as file:
data = file.read()
print(data)I executed the above example code and added the screenshot below.

In this example, we use the with statement to open the file. The advantage of using with is that it automatically closes the file after the block of code is executed, even if an exception is raised.
Read How to Import a Python File from the Same Directory?
CSV Files (.csv)
CSV (Comma-Separated Values) files are often used to store tabular data. Python provides a csv module to work with CSV files:
import csv
with open("sales_data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)I executed the above example code and added the screenshot below.

Check out How to Read an Excel File in Python?
JSON Files (.json)
JSON (JavaScript Object Notation) is a lightweight data interchange format. Python has a built-in json module for handling JSON files:
import json
with open("user_settings.json", "r") as file:
settings = json.load(file)
print(settings)I executed the above example code and added the screenshot below.

Read How to Call a Function from Another File in Python?
Error Handling
When working with files, it’s essential to handle potential errors that may occur. For example, trying to open a file that doesn’t exist will raise a FileNotFoundError. You can use a try-except block to catch and handle such errors:
try:
file = open("nonexistent_file.txt", "r")
except FileNotFoundError:
print("The file does not exist.")Check out How to Replace a Specific Line in a File Using Python?
Conclusion
In this article, I will how to open a file in Python. I discussed using the open() function, explored different file opening modes, and provided examples for common file types like text files, CSV files, and JSON files. We also discussed error handling to ensure your code can gracefully handle issues that may arise when working with files.
You may also like to read:
- How to Read Large CSV Files in Python?
- How to Write Bytes to File in Python?
- How to Create a CSV File in Python?

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.