Skip to main content

Python File Handling: Read, Write, Append Files with Examples

 

✍️Introduction

File Handling in Python allows us to create, read, write, and update files.
It is very important for storing data permanently.

File handling enables Python programs to interact with files stored on disk, making it possible to save program output and retrieve data later.

Using file handling, large amounts of data can be managed efficiently, which is essential for applications like data logging, configuration storage, and report generation.

Python uses the open() function to work with files.


Why File Handling is Important?

  • Store data permanently

  • Read large data

  • Used in real-world applications

  • Useful in projects and interviews


Open a File in Python:

The open() function is used to access a file in Python by specifying its name and the mode of operation.
The mode determines whether the file is opened for reading, writing, or appending, and whether the file is treated as text or binary.

Syntax:

file = open("filename", "mode")

Explanation of Syntax:

  • file → A variable that stores the file object

  • "filename" → Name or path of the file to be opened

  • "mode" → Specifies how the file is opened (read, write, append, etc.)


This syntax allows Python to open a file and perform operations like reading or writing on it.



File Modes:

Following are the modes of files in Python, which specify how a file should be opened and how data can be accessed or modified.

Mode               Description                
rRead (default)
wWrite (creates new file)
aAppend
xCreate file
rbRead binary
wbWrite binary

  • Read mode (r) opens an existing file to read its contents.

  • Write mode (w) creates a new file or overwrites an existing file.

  • Append mode (a) adds new data to the end of a file without deleting existing data.

  • Create mode (x) creates a file and raises an error if the file already exists.

  • Binary modes (rb, wb) are used to read or write non-text files like images, audio, or videos.


1️⃣ Read a File :

Reading a file in Python means accessing and displaying the contents of an existing file.

Example:

file = open("data.txt", "r") # Opens the file in read mode print(file.read()) # Reads and prints the entire file content file.close() # Closes the file after reading

Output (example):

This is sample text stored in the file.

"Code executed successfully" 

Note: The actual output depends on the content present inside data.txt.


Read Line by Line:

Reading a file line by line allows programs to process large files efficiently without loading the entire content into memory.
The readline() method reads one line at a time from the file, making it useful for handling files with multiple lines or structured data.

Example:

file = open("data.txt", "r") # Opens the file in read mode print(file.readline()) # Reads and prints the first line of the file file.close() # Closes the file after reading

Output (example):

This is the first line of the file.

"Code executed successfully" 

Note: The output depends on the actual first line present in data.txt.


Read All Lines:

The readlines() method reads all lines of a file at once and returns them as a list, where each line is an element.
It is useful when you want to process or display all lines together, but it should be used carefully with very large files.

Example:

file = open("data.txt", "r") # Opens the file in read mode print(file.readlines()) # Reads all lines and stores them in a list file.close() # Closes the file after reading

Output (example):

['This is the first line.\n', 'This is the second line.\n',
'This is the third line.']

"Code executed successfully" 

Note: Each line ends with \n (newline character) except possibly the last line.



2️⃣ Write to a File :

Writing to a file in Python means storing new data into a file using write mode.

When a file is opened in write mode (w), Python creates the file if it does not exist.
If the file already exists, its previous content is completely erased before writing new data.

Example:

file = open("data.txt", "w") # Opens the file in write mode file.write("Hello Python") # Writes text into the file file.close() # Closes the file to save changes

Output (example):

['This is the first line.\n', 'This is the second line.\n',
'This is the third line.']

"Code executed successfully" 

Note: Write mode overwrites existing data.


3️⃣ Append to a File :

Appending to a file means adding new data to the end of an existing file without deleting the previous content.

When a file is opened in append mode (a), Python creates the file if it does not exist.
New data is always added at the end of the file, preserving the existing content.

Example:
file = open("data.txt", "a") # Opens the file in append mode file.write("\nWelcome to File Handling") # Adds new text at the end of the file file.close() # Closes the file to save changes

Output (example):

Hello Python Welcome to File Handling


"Code executed successfully" 

Note:Append mode (a) adds new data at the end of the file without removing existing content.
If the file does not exist, Python automatically creates it.


4️⃣ Using with Statement (Best Practice) :

The with statement is used to open files safely and automatically close them after use.

Using with open() is considered best practice because it automatically handles file closing, even if an error occurs.
This makes the code safer, cleaner, and easier to manage.

Example:

with open("data.txt", "r") as file: # Opens the file in read mode print(file.read()) # Reads and prints the file content

✔ Automatically closes file
✔ Safer and cleaner


Check if File Exists :

Checking if a file exists means verifying whether a file is present in the specified location before performing operations on it.

The os.path.exists() function is used to check if a file or folder exists.
It helps prevent errors when trying to open a file that does not exist, making programs more reliable and safe.

Example:

import os # Imports os module for file operations if os.path.exists("data.txt"): # Checks if the file exists print("File exists") # Executes if file is found else: print("File not found") # Executes if file is missing


Example Output (if file exists):

File exists

Example Output (if file does not exist):
File not found


"Code executed successfully" 


Note:It is good practice to check if a file exists
before opening it to avoid runtime errors


Delete a File :

Deleting a file means removing a file permanently from the system.

In Python, the os.remove() function is used to delete a file from the specified location.
This operation permanently removes the file, so it should be used carefully, usually after checking that the file exists.

Example:

import os if os.path.exists("data.txt"): # Checks if file exists os.remove("data.txt") # Deletes the file print("File deleted") else: print("File not found")

Example Output:

File deleted

OR,

File not found


"Code executed successfully" 
Note:If the file does not exist, Python will raise an error,
so it is safer to check before deleting.


Real-Life Example: Save Student Data

This program saves student information into a file for permanent storage.

File handling is commonly used in real-life applications to store records such as student details, marks, and reports.
Using the with statement ensures the file is safely opened and automatically closed after writing.

Example:

with open("student.txt", "w") as file: # Opens student.txt in write mode file.write("Name: Rutuja\n") # Writes student name into the file file.write("Marks: 95") # Writes student marks into the file

Output (example):

Name: Rutuja Marks: 95


"Code executed successfully" 

Note: If the file already exists, write mode (w) will overwrite the previous data.

Common File Functions :

Common file functions are built-in methods used to perform operations like reading, writing, and managing file positions in Python.

These functions help control how data is accessed and modified inside a file.
They allow programmers to read content, write new data, move the file cursor, and check the current position, making file handling more flexible and efficient.

Function             Use       
read()Read full file
write()Write data
close()Close file
seek()Change cursor
tell()Get position


Common Mistakes:

  • Forgetting to close file

  • Using wrong mode

  • Reading non-existing file


File Handling Interview Questions ?

1️⃣ Difference between w and a

Ans:
w (write mode) overwrites the existing file content, while a (append mode) adds new data at the end without deleting existing content.

2️⃣ What is with statement?

Ans:
The with statement is used to open a file safely and automatically close it after use.

3️⃣ How to read large files?

Ans:
Large files can be read efficiently by reading them line by line using readline() or a loop instead of loading the entire file into memory.


Conclusion :

Python file handling is essential for data storage and management.
Mastering it helps you build real-world applications.


💬 Quick Question

What will be the output?

file = open("test.txt", "w") file.write("Python") file.close()

Comment your answer 👇😊


📌 Related Articles

Comments

popular

What Is Python Programming? Features, Uses and Career Scope.

  ✍️ Introduction Python is one of the most popular and beginner-friendly programming languages in the world today. It is widely used for web development, data science, artificial intelligence, automation, and software development. Because of its simple syntax and powerful features, Python is an excellent choice for students, beginners, and professionals. In this article, you will learn what Python programming is, its key features, real-life uses, and the career opportunities it offers. 🧠 What Is Python Programming? Python is a high-level, interpreted programming language created to make coding easy and readable. It allows developers to write programs using simple English-like statements, which makes it ideal for beginners. Python supports multiple programming styles such as procedural, object-oriented, and functional programming. ⭐ Features of Python Easy to learn and understand Simple and readable syntax Interpreted language Platform independent Large standard l...

what is Python Date and Time ? Complete Guide with Examples:

  ✍️ Introduction Python provides powerful tools to work with dates and times . The most commonly used module is datetime . The datetime module allows Python programs to create, manipulate, format, and perform calculations with dates and times easily. Date and time handling is used in: Logging systems Attendance & billing systems Data analysis Real-time applications How To Import Date and Time Module : In Python, the datetime module is used to work with dates , times , and date–time combinations . It is part of Python’s standard library, so no installation is required. You can import it in different ways depending on your need. import datetime Get Current Date and Time: This code obtains the current system date and time as a single datetime object using the datetime module. Example: import datetime now = datetime.datetime.now() print (now) Output: 2026-02-13 11:25:53.445827 "Code executed successfully"  Get Only Date: This code retrieves t...

Features of Python Programming Language Explained with Examples

✍️ Introduction Python is one of the most popular programming languages because of its powerful and easy-to-use features. It is designed to make programming simple, readable, and efficient. Python is widely used by beginners as well as professionals due to its flexibility and strong community support. In this article, we will discuss the main features of Python programming language in simple English with easy examples. 🧠 What Are Features of Python? Features of Python are the special characteristics that make it different from other programming languages. These features help programmers write clean, readable, and efficient code with less effort. ⭐ Key Features of Python Programming Language 1️⃣ Easy to Learn and Easy to Use Python has a simple syntax that is close to the English language. This makes it very easy for beginners to learn and understand programming concepts. Example: print("Hello, World!") 2️⃣ Interpreted Language Python is an interpreted language, which me...

Python Operators: Types with Examples

 ✍️Introduction In Python, operators are symbols used to perform operations on variables and values. Operators help us do calculations, comparisons, and logical decisions in programs. In this article, you will learn: • What Python operators are • Types of Python operators • Simple examples for each type