File Handling in Python: Complete Guide With Examples

By Sriram

Updated on Jul 10, 2026 | 14 min read | 4.22K+ views

Share:

Key Takeaway

  • File handling in Python lets you create, read, write, and manage files directly from your code using the built-in open() function.
  • Different Modes are used for different tasks. r to read, w to write (overwrites), a to append, and rb/wb for binary files. Picking the wrong mode can wipe your data.
  • Always use with open(...) as file: syntax; it closes files automatically, even if an error occurs, so skip manual close() calls.
  • Handle errors: Wrap file operations in try-except to catch FileNotFoundError or PermissionError instead of letting your script crash.
  • Python's built-in csv module (with reader, writer, DictReader, DictWriter) handles tabular data without needing external libraries.

In this blog, you will get a complete walkthrough of file handling in Python, from the basics to real coding examples. We will cover file-handling modes in Python, how to read and write files, work with CSV data, handle errors properly, and see complete, working programs. By the end, you will be able to write your own file-handling program in Python with confidence. 

Understanding AI concepts is only the first step toward building a successful career in this field. Explore AI courses offered by upGrad and compare programs designed to help you develop practical, industry-ready skills.

What Is File Handling in Python

File handling is a set of built-in tools and functions that let you interact with files stored on your computer, without leaving your Python script. It is the process of creating, opening, reading, writing, and closing files directly from your code.

Instead of manually typing data every time, Python lets you store information in files and pull it back whenever you need it. Whether you are building a small script or a full application, file handling in Python is one of the first practical skills you need to master.

Python treats files as objects. When you open a file, Python gives you a file object that you can use to perform actions like reading or writing. This is what makes file handling in Python so simple compared to some other languages.

Here is a quick way to explain file handling in Python: think of a file as a notebook. You can open the notebook, read what is written, add new notes, erase old ones, or close it and put it away. Python's file handling functions do exactly this, just with code instead of your hands.

Also Read: Python Tutorial: Setting Up, Tools, Features, Applications, Benefits, Comparison

Why File Handling in Python Matters

Files let your Python programs save and reuse data even after the script stops running, instead of losing everything once it exits. This makes file handling essential for tasks like logging, reporting, automation, and working with real-world data. File handling matters as it:

  • It lets programs save data permanently, even after the script stops running.
  • It helps you work with real-world data like logs, reports, and configuration files.
  • It is needed for tasks like data analysis, automation, and web scraping.
  • It removes the need to hardcode data inside your script.

Also Read: What is Python Web Scraping?

Types of Files Python Can Handle

Python can work with several types of files, each suited to a different data format, from plain text to structured records. Knowing which type you're dealing with helps you pick the right mode and method for reading or writing it.

File Type 

Description 

Common Extension 

Text files  Store readable text data  .txt 
CSV files  Store tabular data separated by commas  .csv 
JSON files  Store structured data as key-value pairs  .json 
Binary files  Store non-text data like images or audio  .jpg, .mp3, .exe 

Also Read: Difference between Text File and Binary File

Python's built-in open() function works with all of these, though binary files need a slightly different mode, which we will cover next.

If someone asks you to explain file handling in Python during an interview or a class, this is the core idea to remember: it is about interacting with files using Python's built-in functions, without depending on any external software.

File Handling Modes in Python

Before you open a file, Python needs to know what you plan to do with it. That is where file handling modes in Python come in. A mode tells Python whether you want to read, write, append, or do something else with the file.

Here are the most commonly used file handling modes in Python:

Mode 

Meaning 

What Happens 

Read  Opens file for reading. File must exist 
Write  Creates a new file or overwrites an existing one 
Append  Adds new data at the end of the file 
r+  Read and Write  Opens file for both reading and writing 
w+  Write and Read  Overwrites file and allows reading 
a+  Append and Read  Adds data at the end and allows reading 
rb  Read Binary  Opens a binary file for reading 
wb  Write Binary  Opens a binary file for writing 

Choosing the Right Mode

Picking the correct mode matters a lot. If you use w mode by mistake on a file you meant to only read, you will erase everything in it. Here is a simple rule of thumb:

  • Use r when you only need to read data.
  • Use w when you want to create a new file or overwrite existing content.
  • Use a when you want to keep existing content and just add more.
  • Use rb or wb when working with non-text files, such as images.
# Opening a file in read mode 
file = open("notes.txt", "r") 

Properly understanding file handling modes in Python will save you from a lot of accidental data loss. Always double check the mode before running a script that writes to a file.

If you're looking to turn Python fundamentals into a career in AI and machine learning, upGrad's Executive Diploma in Machine Learning & AI with MLOps, Gen AI & Agentic AI can help you get there. The program covers everything from core Python and data handling to building, deploying, and scaling real-world ML and AI systems, including MLOps pipelines, Generative AI, and Agentic AI applications.

Machine Learning Courses to upskill

Explore Machine Learning Courses for Career Progression

360° Career Support

Executive Diploma12 Months
background

Liverpool John Moores University

Master of Science in Machine Learning & AI

Double Credentials

Master's Degree18 Months

Opening and Closing Files in Python

Once you know the mode, the next step is actually opening the file. Python's open() function is the starting point for almost every file handling task.

The open() Function

file = open("data.txt", "r") 

This line opens data.txt in read mode and stores the file object in the variable file. You can now call methods on this object to read its content.

Closing a File

Every file you open should be closed once you are done. This frees up system resources and makes sure your data is saved properly.

file = open("data.txt", "r") 
content = file.read() 
file.close() 

Forgetting to close a file is a common mistake, especially for beginners. It can lead to locked files or data that does not get saved correctly.

Also Read: Python File Handling: Opening and Closing Files in Python with Examples

Using the with Statement

A cleaner and safer way to handle files is with the with statement. It automatically closes the file for you, even if an error occurs while working with it.

with open("data.txt", "r") as file: 
   content = file.read() 

Notice there is no need to call file.close() here. Python takes care of it once the code inside the with block finishes running.

open() vs with open()

Aspect 

open() and close() 

with open() 

File closing  Manual, must call close()  Automatic 
Error handling  Risky if an error skips close()  Safer, closes file even on error 
Code length  Slightly longer  Shorter and cleaner 
Recommended for  Quick scripts  Most real-world code 

Most Python developers prefer the with statement because it is short, readable, and reduces the chance of leaving files open by mistake.

Reading Files in Python

Reading data is one of the most common file handling tasks. Python gives you three main methods to do this, and each one works a little differently.

read(), readline(), and readlines()

Method 

What It Returns 

Best Used For 

read()  Entire file content as one string  Small files 
readline()  One line at a time  Reading line by line manually 
readlines()  List of all lines  When you need each line as a separate item 
with open("data.txt", "r") as file: 
   print(file.read()) 
with open("data.txt", "r") as file: 
   line = file.readline() 
   print(line) 
with open("data.txt", "r") as file: 
   lines = file.readlines() 
   print(lines) 
 

If you were asked to explain file handling in Python to a beginner, reading methods are usually the easiest place to start, since the output is something you can see right away.

Reading a File Line by Line

For large files, reading everything at once is not ideal. It can slow down your program or use too much memory. Instead, loop through the file directly:

with open("data.txt", "r") as file: 
   for line in file: 
       print(line.strip()) 

This method reads one line at a time and is the most memory-efficient way to process large text files.

Writing and Appending to Files in Python

Reading is only half the job. Most real applications also need to write data back into files, whether that is logs, reports, or saved user input.

Writing to a File

with open("output.txt", "w") as file: 
   file.write("Hello, this is a new file.") 

Remember, w mode overwrites the file completely. If output.txt already had content, it will be gone after this runs.

Also Read: How To Write to a File in Python

Appending to a File

with open("output.txt", "a") as file: 
   file.write("\nThis line gets added at the end.") 

Append mode is useful when you want to keep a running log without deleting older entries.

Also Read: Append in Python

Write Mode vs Append Mode

Feature 

Write Mode (w) 

Append Mode (a) 

Existing content  Erased  Kept 
New content  Replaces file  Added at the end 
Common use  Creating fresh reports  Logging, tracking history 

Knowing what is file handling in Python at a code level, and not just in theory, means you should be able to write, run, and read back a file without checking documentation every time.

Subscribe to upGrad's Newsletter

Join thousands of learners who receive useful tips

Promise we won't spam!

Common File Operations in Python

Beyond reading and writing, Python also lets you manage files directly, similar to how you would in a file explorer.

Checking if a File Exists

import os 
 
if os.path.exists("data.txt"): 
   print("File found") 
else: 
   print("File does not exist") 
 

Creating, Deleting, and Renaming Files

import os 
 
# Create a new file 
open("newfile.txt", "w").close() 
 
# Rename a file 
os.rename("newfile.txt", "renamed.txt") 
 
# Delete a file 
os.remove("renamed.txt") 
 

Working With File Paths

Python offers two main ways to handle file paths: the older os module and the newer pathlib module.

# Using os module 
import os 
path = os.path.join("folder", "data.txt") 

# Using pathlib module
from pathlib import Path
path = Path("folder") / "data.txt"

pathlib is generally considered cleaner and more readable, especially when working across different operating systems.

File Exception Handling in Python

Things do not always go smoothly. A file might be missing, or you might not have permission to open it. This is where file exception handling in Python becomes important.

Common File Errors

  • FileNotFoundError: The file does not exist at the given path.
  • PermissionError: You do not have the right to access the file.
  • IsADirectoryError: You tried to open a folder as if it were a file.
  • UnicodeDecodeError: The file contains characters Python cannot read with the current encoding.

Using try-except for File Exception Handling

try: 
   with open("missing.txt", "r") as file: 
       data = file.read() 
except FileNotFoundError: 
   print("The file was not found.") 
except PermissionError: 
   print("You do not have permission to open this file.") 

Good file exception handling in Python means your program does not crash when something unexpected happens. Instead, it shows a clear message and keeps running or exits gracefully.

Handling Exceptions While Closing a File

Even closing a file can sometimes raise an error, especially with unusual file systems. Wrapping the whole block in a try-except, or simply using with, avoids this problem since with closes the file automatically, no matter what happens inside the block.

Also Read: Exception Handling in Python

CSV File Handling in Python

CSV files are one of the most common formats you will work with, especially for spreadsheets, reports, and data exports. Python has a built-in csv module that makes csv file handling in Python straightforward.

Reading a CSV File

import csv 
 
with open("data.csv", "r") as file: 
   reader = csv.reader(file) 
   for row in reader: 
       print(row) 
 

Writing to a CSV File

import csv 
 
with open("output.csv", "w", newline="") as file: 
   writer = csv.writer(file) 
   writer.writerow(["Name", "Age", "City"]) 
   writer.writerow(["Amit", 28, "Delhi"]) 
 

Using DictReader and DictWriter

For readability, you can also read and write CSV files as dictionaries, where each column header becomes a key.

import csv 
 
with open("data.csv", "r") as file: 
   reader = csv.DictReader(file) 
   for row in reader: 
       print(row["Name"], row["Age"]) 
 

This approach to CSV file handling in Python is especially useful when working with data that has many columns, since you can call fields by name instead of remembering their position.

File Handling Examples in Python

Reading the theory is useful, but writing an actual file handling program in Python is what makes it click. Here are a few practical examples you can try.

Example 1: Simple File Handling Program

with open("greeting.txt", "w") as file: 
   file.write("Welcome to file handling in Python!") 
 
with open("greeting.txt", "r") as file: 
   print(file.read()) 

Example 2: Word Counter

with open("data.txt", "r") as file: 
   content = file.read() 
   words = content.split() 
   print("Total words:", len(words)) 

Example 3: Copying Content Between Files

with open("source.txt", "r") as source: 
   with open("destination.txt", "w") as destination: 
       destination.write(source.read()) 

Example 4: Logging User Actions

import datetime 
 
def log_action(action): 
   with open("activity.log", "a") as file: 
       file.write(f"{datetime.datetime.now()}: {action}\n") 
 
log_action("User logged in") 
log_action("User uploaded a file") 
 

These file handling examples in Python cover the most common patterns you will use in real projects: writing, reading, copying, and logging data. Practicing these file handling examples in Python is the fastest way to get comfortable with the syntax.

Common Mistakes to Avoid in File Handling in Python

Even experienced developers slip up on a few basics when writing a file handling program in Python. Knowing these mistakes in advance will save you time later.

  • Forgetting to close files. If you skip with, you must remember to call close() yourself. Leaving files open can lock them or cause data loss.
  • Using the wrong mode. Opening a file in w mode when you meant a mode will erase existing content instantly, with no warning.
  • Ignoring encoding issues. Text files with special characters can throw errors if you do not specify the correct encoding, such as utf-8.
  • Not handling missing files. Skipping file exception handling in Python means your script crashes the moment a file is missing, instead of showing a clear message.
  • Hardcoding file paths. A script that only works on your machine because of a fixed file path will break the moment someone else runs it.
  • Reading large files in one go. Using read() on a huge file can consume a lot of memory. Looping line by line is safer for large csv file handling in Python tasks or big text logs.

To explain file handling in Python in one line: it is simple once you respect the mode you choose, close what you open, and plan for errors that might arise. Most beginner mistakes come from skipping one of these three steps.

Best Practices for File Handling in Python

Following a few simple habits will save you a lot of debugging time later.

  • Always use the with statement instead of manually calling open() and close()
  • Double-check the file mode before writing, especially with w mode
  • Use try-except blocks around file operations that might fail
  • Close files as soon as you are done working with them
  • Use pathlib for cleaner, cross-platform file paths
  • Avoid hardcoding file paths; use relative paths or configuration variables
  • Specify file encoding explicitly when working with text that has special characters

Following these practices makes your file handling in Python code more reliable and easier to maintain, especially as your projects grow larger. If you can explain file handling in Python using these habits, you already understand more than most beginners who only memorize the syntax.

Conclusion

File handling in Python comes down to a few core building blocks: opening a file, choosing the right mode, reading or writing data, and closing it properly. Once you understand these, along with reading and writing CSV files and handling exceptions, the rest is just practice. Try the examples in this blog, tweak them, and build a few small scripts of your own. That hands-on repetition is what makes file handling feel natural, and it sets you up well for bigger tasks like data processing, automation, and building applications that manage real-world files.

Want personalized guidance on Artificial Intelligence and upskilling? Speak with an expert for a free 1:1 counselling session today.

Frequently Asked Questions(FAQs)

1. What is file handling in Python used for?

File handling in Python is used to create, read, write, and manage files directly from your code. It allows programs to store data permanently, work with logs, process reports, and exchange information with other applications without hardcoding values in the script.

2. How many file handling modes are there in Python?

Python offers several file handling modes, including read, write, append, and their combined read-write versions, along with binary modes for non-text files. Choosing the correct mode is important since some modes, like write mode, overwrite existing file content.

3. What is the difference between read() and readlines() in Python?

The read() method returns the entire file content as a single string, while readlines() returns a list where each item is one line from the file. readlines() is useful when you need to process or loop through individual lines separately.

4. Why should I use the with statement for file handling in Python?

The with statement automatically closes the file once the code block finishes, even if an error occurs during execution. This makes your file handling in Python code safer and shorter compared to manually calling open() and close().

5. How do I fix a FileNotFoundError in Python?

A FileNotFoundError usually means the file path is incorrect or the file does not exist. Check the spelling of the file name, confirm the file is in the expected folder, and consider using os.path.exists() before opening the file.

6. Can Python read and write CSV files without external libraries?

Yes, Python's built-in csv module handles csv file handling in Python without needing any third-party packages. It supports reading, writing, and even working with CSV data as dictionaries using DictReader and DictWriter.

7. What is the difference between text mode and binary mode in Python?

Text mode treats file content as readable strings and is used for files like .txt or .csv. Binary mode, indicated by b in the mode string, handles raw bytes and is required for files like images, audio, or executables.

8. How do I handle exceptions while working with files in Python?

File exception handling in Python is typically done using try-except blocks around file operations. This lets you catch specific errors like FileNotFoundError or PermissionError and respond with a clear message instead of letting the program crash.

9. What is the difference between os and pathlib for file handling?

The os module is the older, function-based way to work with file paths, while pathlib offers an object-oriented approach that many developers find more readable. Both work well, but pathlib is generally recommended for new projects.

10. Is it necessary to close a file after opening it in Python?

Yes, closing a file frees system resources and ensures data is properly saved to disk. Using the with statement is the safest way to guarantee a file gets closed automatically, without needing to remember to call close() manually.

11. How do I write a simple file handling program in Python for beginners?

A simple file handling program in Python can start with opening a file in write mode, adding some text, then reading it back. Practicing small file handling examples in Python, like word counters or basic logging scripts, helps build confidence quickly.

Sriram

617 articles published

Sriram K is a Senior SEO Executive with a B.Tech in Information Technology from Dr. M.G.R. Educational and Research Institute, Chennai. With over a decade of experience in digital marketing, he specia...

Speak with AI & ML expert

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive Program in Generative AI for Leaders

76%

seats filled

View Program

Top Resources

Recommended Programs

LJMU

Liverpool John Moores University

Master of Science in Machine Learning & AI

Double Credentials

Master's Degree

18 Months

IIITB
bestseller

IIIT Bangalore

Executive Diploma in Machine Learning and AI

360° Career Support

Executive Diploma

12 Months

IIITB
new course

IIIT Bangalore

Executive Programme in Generative AI & Agentic AI for Leaders

India’s #1 Tech University

Dual Certification

5 Months