Python File Handling – Read, Write and Append Files with Examples





Python File Handling – Read, Write and Append Files with Examples

📅 Published on Code with Py📂 Category: Python Basics⏱️ Reading time: ~15 min
















Every real-world Python program works with files — saving student records, reading a configuration file, writing logs, or storing user data. Without file handling, your program loses all its data the moment it stops running. In this complete guide, you will learn how to create, open, read, write, and append files in Python. You will also learn the safest way to work with files using the with statement. Every concept is explained from scratch with original examples and real output.

📋 Table of Contents

  1. Why Do We Need File Handling?
  2. Types of Files in Python
  3. Opening a File – The open() Function
  4. File Opening Modes Explained
  5. Reading a File – read(), readline(), readlines()
  6. Writing to a File – write() and writelines()
  7. Appending to a File
  8. The with Statement – Best Practice
  9. Checking if a File Exists
  10. Deleting and Renaming Files
  11. Working with File Paths
  12. Real-Life Projects
  13. Practice Problems
  14. FAQ

1. Why Do We Need File Handling?

Think about what happens when you close a Python program. All the variables, lists, and dictionaries you created disappear completely — they exist only in your computer's memory (RAM), and RAM is temporary.

Now think about a school management system. You collected marks for 200 students. If you close the program, all that data vanishes. That is a serious problem in real programs.

File handling solves this problem. It lets your Python program save data permanently to a file on your computer's storage — so the data survives even after the program closes. Next time you run the program, it reads the data back from the file and picks up exactly where it left off.

Without File Handling

Data lives only in RAM. Program closes → all data gone. Cannot share data between runs. Cannot build persistent apps.

With File Handling

Data saved to disk permanently. Program can reload it anytime. Share data between programs. Build real-world applications.


2. Types of Files in Python

Python can work with two types of files. Knowing the difference helps you choose the right mode when opening them.

TypeWhat it storesExamplesCan you read it?
Text FilesHuman-readable characters.txt, .csv, .py, .html, .jsonYes — open in Notepad
Binary FilesRaw bytes — not readable as text.jpg, .mp3, .pdf, .exe, .zipNo — needs special software
This guide focuses on text files — they are what most beginners need. Binary file handling uses the same functions but with "rb" and "wb" modes instead.

3. Opening a File – The open() Function

Before you can read or write a file, you must first open it. Python's built-in open() function does this. It returns a file object that you use to perform operations on the file.

# Syntax
file_object = open("filename", "mode")

# Example
f = open("students.txt", "r")   # open for reading

The open() function takes two main arguments:

  • filename — the name of the file (can include full path)
  • mode — what you want to do with the file (read, write, append etc.)
Always close the file after you are done using it. An unclosed file can cause data loss or lock the file on Windows. Use f.close() or better — use the with statement which closes automatically.

4. File Opening Modes Explained

The mode tells Python exactly what you plan to do with the file. Each mode behaves differently — using the wrong one can accidentally erase your data.

ModeNameWhat it doesFile must exist?
"r"ReadOpens file for reading only. Cannot modify.Yes — error if missing
"w"WriteCreates file if not exists. Overwrites if it does.No — creates new file
"a"AppendAdds content to end. Does not erase existing data.No — creates new file
"x"CreateCreates new file. Fails if file already exists.Must NOT exist
"r+"Read+WriteRead and write. File must exist.Yes
"rb"Read BinaryRead binary files like images, PDFsYes
"wb"Write BinaryWrite binary filesNo — creates new
Be very careful with "w" mode — it erases the entire file content before writing. If you want to add content without deleting existing data, always use "a" (append) mode.

5. Reading a File – read(), readline(), readlines()

Once a file is opened in read mode, Python gives you three ways to read its content depending on how much you need.

First — Create a sample file to work with

# Create a text file with some student data
f = open("students.txt", "w")
f.write("Rohan - 85\n")
f.write("Priya - 92\n")
f.write("Arjun - 67\n")
f.write("Meera - 78\n")
f.close()
print("File created successfully!")
File created successfully!

read() – Read entire file as one string

f = open("students.txt", "r")
content = f.read()
print(content)
f.close()
Rohan - 85
Priya - 92
Arjun - 67
Meera - 78

read(n) – Read only n characters

f = open("students.txt", "r")
print(f.read(10))   # Read first 10 characters only
f.close()
Rohan - 85

readline() – Read one line at a time

f = open("students.txt", "r")
print(f.readline())   # First line
print(f.readline())   # Second line
print(f.readline())   # Third line
f.close()
Rohan - 85

Priya - 92

Arjun - 67

readlines() – Read all lines into a list

f = open("students.txt", "r")
lines = f.readlines()
print(lines)
print(f"\nTotal lines: {len(lines)}")
f.close()
['Rohan - 85\n', 'Priya - 92\n', 'Arjun - 67\n', 'Meera - 78\n']

Total lines: 4

Loop through file line by line (Most Efficient)

f = open("students.txt", "r")
for line in f:
    print(line.strip())   # strip() removes extra \n
f.close()
Rohan - 85
Priya - 92
Arjun - 67
Meera - 78
Looping through a file line by line is the most memory-efficient method. It does not load the entire file into memory at once — perfect for large files with thousands of lines.

6. Writing to a File – write() and writelines()

Use "w" mode to write content to a file. If the file does not exist, Python creates it. If it already exists, Python erases all its content first and then writes the new content.

write() – Write a single string

f = open("output.txt", "w")
f.write("Python File Handling\n")
f.write("Written by Code with Py\n")
f.write("Learning is fun!\n")
f.close()
print("File written successfully.")
File written successfully.

writelines() – Write a list of strings at once

students = [
    "Rohan   - 85\n",
    "Priya   - 92\n",
    "Arjun   - 67\n",
    "Meera   - 78\n"
]

f = open("marks.txt", "w")
f.writelines(students)
f.close()
print("All student marks saved.")
All student marks saved.
write() takes a single string and does not add a newline automatically — you must add \n yourself. writelines() takes a list of strings but also does not add newlines — include \n in each string.

7. Appending to a File

Append mode ("a") adds new content to the end of an existing file without deleting anything. This is what you need when you want to keep adding new records — like adding a new student to a marks file.

# marks.txt already has 4 students from previous step
f = open("marks.txt", "a")
f.write("Kavya   - 95\n")
f.write("Ravi    - 71\n")
f.close()

# Read back to verify
f = open("marks.txt", "r")
print(f.read())
f.close()
Rohan   - 85
Priya   - 92
Arjun   - 67
Meera   - 78
Kavya   - 95
Ravi    - 71
The golden rule — use "w" when creating a fresh file and "a" when updating an existing file. Mixing them up is the most common beginner mistake in file handling.

8. The with Statement – Best Practice

The with statement is the recommended way to work with files in Python. It automatically closes the file as soon as the block finishes — even if an error occurs inside. You never need to call f.close() manually.

Without with (old way — not recommended)

f = open("data.txt", "r")
content = f.read()
print(content)
f.close()   # Easy to forget this!

With statement (correct, modern way)

with open("students.txt", "r") as f:
    content = f.read()
    print(content)
# File is closed automatically here — no f.close() needed
Rohan - 85
Priya - 92
Arjun - 67
Meera - 78

Writing with the with statement

with open("notes.txt", "w") as f:
    f.write("This is written using the with statement.\n")
    f.write("The file closes automatically after this block.\n")

print("File saved safely.")
File saved safely.

Read and write in same with block using r+

with open("students.txt", "r+") as f:
    data = f.read()
    print("Original:")
    print(data)
    f.write("\nSanjay - 88")   # Append at current position
    print("New entry added.")
Original:
Rohan - 85
Priya - 92
Arjun - 67
Meera - 78
New entry added.
Always use the with statement for file operations. It is safer, cleaner, and the industry-standard way to handle files in Python. Professional Python developers never use open() without with.

9. Checking if a File Exists

Before opening a file for reading, it is a good practice to check whether it actually exists — otherwise Python will throw a FileNotFoundError. Use Python's os.path module for this.

import os

filename = "students.txt"

if os.path.exists(filename):
    with open(filename, "r") as f:
        print(f.read())
else:
    print(f"File '{filename}' does not exist!")
Rohan - 85
Priya - 92
Arjun - 67
Meera - 78

Combine with exception handling for extra safety

try:
    with open("grades.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("File not found. Please check the filename.")
except PermissionError:
    print("You do not have permission to read this file.")
File not found. Please check the filename.

10. Deleting and Renaming Files

Python's os module lets you delete and rename files from within your program.

import os

# Rename a file
if os.path.exists("notes.txt"):
    os.rename("notes.txt", "my_notes.txt")
    print("File renamed successfully.")

# Delete a file
if os.path.exists("output.txt"):
    os.remove("output.txt")
    print("File deleted successfully.")
File renamed successfully.
File deleted successfully.
Always check if the file exists before trying to delete or rename it. Calling os.remove() on a file that does not exist raises a FileNotFoundError and crashes your program.

11. Working with File Paths

When you open a file by just its name like "students.txt", Python looks for it in the current working directory. For files in other locations, you need to provide the full path.

import os

# Find current working directory
print(os.getcwd())

# Absolute path (Windows)
f = open(r"C:\Users\Rohan\Documents\students.txt", "r")

# Absolute path (Linux / Mac)
f = open("/home/rohan/documents/students.txt", "r")

# Build path safely using os.path.join()
folder = "data"
file   = "students.txt"
path   = os.path.join(folder, file)
print(path)   # data/students.txt (works on all OS)
/home/user/my_project
data/students.txt
Always use os.path.join() to build file paths — never manually join with "/" or "\"os.path.join() automatically uses the correct separator for Windows, Linux, or Mac.

12. Real-Life Projects

Project 1 – Student Marks Manager

def save_marks(name, marks):
    with open("marks.txt", "a") as f:
        f.write(f"{name},{marks}\n")
    print(f"Saved: {name} - {marks}")

def show_all_marks():
    print("\n--- Student Mark Sheet ---")
    try:
        with open("marks.txt", "r") as f:
            for line in f:
                name, marks = line.strip().split(",")
                grade = "Pass" if int(marks) >= 40 else "Fail"
                print(f"{name:10} | {marks:3} | {grade}")
    except FileNotFoundError:
        print("No records found yet.")

# Save some students
save_marks("Rohan",  85)
save_marks("Priya",  92)
save_marks("Arjun",  35)
show_all_marks()
Saved: Rohan - 85
Saved: Priya - 92
Saved: Arjun - 35

--- Student Mark Sheet ---
Rohan      |  85 | Pass
Priya      |  92 | Pass
Arjun      |  35 | Fail

Project 2 – Daily Diary App

from datetime import date

def write_diary(entry):
    today = date.today()
    with open("diary.txt", "a") as f:
        f.write(f"\n[{today}]\n")
        f.write(entry + "\n")
        f.write("-" * 40 + "\n")
    print("Diary entry saved!")

def read_diary():
    try:
        with open("diary.txt", "r") as f:
            print(f.read())
    except FileNotFoundError:
        print("No diary entries yet!")

write_diary("Today I learned Python file handling. It is very useful!")
write_diary("Completed 3 practice problems and all passed.")
read_diary()
Diary entry saved!
Diary entry saved!

[2026-04-29]
Today I learned Python file handling. It is very useful!
----------------------------------------

[2026-04-29]
Completed 3 practice problems and all passed.
----------------------------------------

13. Practice Problems

Basic reading

  1. Read a file and print its content
  2. Read only the first 3 lines
  3. Count total lines in a file
  4. Find a specific word in a file
  5. Read a file and store lines in a list

Writing tasks

  1. Write your name and age to a file
  2. Write 5 city names using writelines()
  3. Overwrite an existing file with new data
  4. Append 3 new entries to an existing file
  5. Write and then read back the same file

with statement

  1. Use with to read any text file
  2. Use with to write and append
  3. Handle FileNotFoundError with try-except
  4. Check if file exists before reading
  5. Rename a file using os.rename()

Real-life challenges

  1. Build a student marks manager
  2. Create a shopping list saver app
  3. Count words in a text file
  4. Copy content of one file to another
  5. Build a simple notes app with save/load
For every file practice problem, always test with a file that does not exist and one that does — this helps you catch bugs early.

✅ Quick Summary – What You Learned

  • File handling lets your program save data permanently beyond the program's lifetime
  • open(filename, mode) opens a file and returns a file object
  • "r" reads, "w" writes (erases first), "a" appends (safe), "x" creates new only
  • read() reads all, readline() reads one line, readlines() returns a list of lines
  • write() writes a string, writelines() writes a list — both need \n manually
  • Always use the with statement — it closes the file automatically
  • Use os.path.exists() to check if file exists before reading
  • Combine file handling with exception handling for bulletproof programs

Frequently Asked Questions (FAQ)

Q1. What is the difference between write mode "w" and append mode "a"?

Write mode "w" completely erases the file's existing content before writing new data. If the file does not exist, it creates a new one. Append mode "a" adds new content to the end of the file without touching what is already there. Always use "a" when you want to keep existing data and just add more records.

Q2. What happens if I open a file in read mode but the file does not exist?

Python raises a FileNotFoundError. To handle this gracefully, either check if the file exists first using os.path.exists(), or wrap your open() call in a try-except block and catch the FileNotFoundError.

Q3. Why should I use the with statement instead of open() and close()?

The with statement guarantees the file is closed even if an error occurs inside the block. Without it, if your code raises an exception between open() and close(), the file stays open — which can cause data corruption or lock issues on Windows. The with statement makes file handling safe, clean, and professional.

Q4. What is the difference between read(), readline(), and readlines()?

read() reads the entire file content as a single string. readline() reads one line each time it is called — useful for processing line by line. readlines() reads all lines and returns them as a list of strings. For large files, looping directly over the file object is the most memory-efficient approach.

Q5. How do I write a list of items to a file?

Use writelines() to write a list of strings at once. Make sure each string in the list ends with \n so items appear on separate lines. Alternatively, loop through the list and call write() for each item inside the loop.

Q6. Can I read and write to the same file at the same time?

Yes, using the "r+" mode which opens the file for both reading and writing. The file must already exist. The read/write pointer starts at the beginning, so reading moves it forward and writing starts from where reading stopped. For most beginner use cases, it is cleaner to read first, then open again in write or append mode.


Found this post helpful? Share it with a friend learning Python. Try the practice problems and drop your solutions in the comments!

"A program that cannot save its data is like a notebook with disappearing ink. File handling gives your code a permanent memory." 

Comments

Popular posts from this blog

Python Strings – A Complete Guide for Beginners (with Examples)

Python Control Flow Statements – Complete Guide with Real-Life Examples

Python Loops Explained – for Loop and while Loop with Examples and Output