File Handling in Python

In the real world, data is not always stored in variables or lists. Most of the time, it lives in files—whether it’s a text file, logs, configuration data, images, or even large datasets.

That’s where File Handling in Python comes into play.

This guide will walk you through everything about opening, reading, writing, appending, closing, and managing files—and also cover advanced concepts like file modes, context managers, error handling, binary files, and JSON/CSV file handling.

File Handling in Python

What is File Handling?

File handling is simply the way we open, read, write, modify, and close files in Python.

Python provides a built-in function open() to work with files.


Opening a File

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

Here:

  • "example.txt" → file name
  • "r" → mode (read mode)

File Modes in Python

ModeMeaningExample
"r"Read (default). Error if file doesn’t existopen("file.txt", "r")
"w"Write (creates new or overwrites existing)open("file.txt", "w")
"a"Append (creates new if not exists, adds to end)open("file.txt", "a")
"x"Exclusive creation (error if file exists)open("file.txt", "x")
"b"Binary mode (images, videos, PDFs)open("file.jpg", "rb")
"t"Text mode (default)open("file.txt", "rt")
"+"Read + Writeopen("file.txt", "r+")

Read More: Lists in Python


Reading from a File

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

Other ways:

# Read only first 10 characters
print(file.read(10))

# Read single line
print(file.readline())

# Read all lines in a list
lines = file.readlines()
print(lines)

Loop through lines:

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

Writing to a File

file = open("example.txt", "w")
file.write("Hello, Python learners!\n")
file.write("This is file handling in action.\n")
file.close()

⚠ Using "w" overwrites the file.

To append new content:

with open("example.txt", "a") as file:
    file.write("This line is appended.\n")

Best Practice: Using with Statement

with ensures files close automatically:

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

Reading & Writing Together

with open("notes.txt", "w+") as file:
    file.write("First note.\n")
    file.seek(0)  # Move pointer back to start
    print(file.read())

Working with File Paths

  • Absolute path:
with open("C:/Users/SmartTejas/Documents/data.txt", "r") as file:
    print(file.read())
  • Relative path:
with open("data.txt", "r") as file:
    print(file.read())

Error Handling in File Handling

Sometimes the file may not exist. Use try-except:

try:
    with open("missing.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("File not found. Please check the filename.")

Working with Binary Files

with open("image.jpg", "rb") as file:
    data = file.read()
    print(f"File size: {len(data)} bytes")

Writing binary files:

with open("copy.jpg", "wb") as file:
    file.write(data)

File Handling with JSON

JSON (JavaScript Object Notation) is common for storing structured data.

import json

data = {"name": "Tejas", "age": 25, "city": "Raipur"}

# Writing JSON
with open("data.json", "w") as file:
    json.dump(data, file)

# Reading JSON
with open("data.json", "r") as file:
    loaded = json.load(file)
    print(loaded)

File Handling with CSV

CSV (Comma-Separated Values) is used in spreadsheets.

import csv

# Writing CSV
with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "Course"])
    writer.writerow(["Ankit", 22, "Python"])
    writer.writerow(["Riya", 21, "Data Science"])

# Reading CSV
with open("students.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Useful File Methods

MethodUse
file.read(size)Read characters
file.readline()Read one line
file.readlines()Read all lines as list
file.write(str)Write string
file.writelines(list)Write multiple lines
file.seek(pos)Move pointer
file.tell()Current pointer position
file.close()Close file

Real-Life Project: Simple Contact Saver

# Contact Saver using File Handling

def add_contact():
    name = input("Enter name: ")
    phone = input("Enter phone: ")

    # Read all contacts first
    with open("contacts.txt", "r") as file:
        contacts = file.read()

    if phone in contacts:
        print(f"This {phone} is already saved in your contact.")
    else:
        with open("contacts.txt", "a") as file:
            file.write(f"{name} - {phone}\n")
        print("Contact saved!")

def view_contacts():
    with open("contacts.txt", "r") as file:
        print("Your Contacts:")
        for line in file:
            print(line.strip())

while True:
    choice = input("\n1. Add Contact\n2. View Contacts\n3. Exit\nChoose: ")
    if choice == "1":
        add_contact()
    elif choice == "2":
        view_contacts()
    elif choice == "3":
        break
    else:
        print("Invalid choice.")

Final Thoughts

File handling is a core Python skill.
With it, you can:

  • Save & load user data
  • Store logs and configurations
  • Work with CSV/JSON for data science
  • Even handle binary files like images & PDFs

FAQs – File Handling in Python

File modes define how a file is opened. Common modes:

  • "r" → read

  • "w" → write (overwrite)

  • "a" → append

  • "b" → binary mode

  • "t" → text mode (default)

  • "+" → read + write

Using with open() is recommended because it automatically closes the file once the block is finished, preventing memory leaks.

  • JSON → for structured hierarchical data (like dictionaries)

  • CSV → for tabular data (rows and columns, like Excel)

  • Storing user contacts

  • Writing log files

  • Reading configuration settings

  • Processing CSV/JSON for data analysis

  • Saving scraped data from the web

What’s Next?

In the next post, we’ll learn about the Error Handling in Python

Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Translate »
Scroll to Top