Python Tutorial chapters (19)
  1. 01Python Introduction
  2. 02Python Syntax, Keywords & Operators
  3. 03Python Variables & Data Types
  4. 04Python Strings
  5. 05Python Control Statements
  6. 06Python Lists
  7. 07Python Tuples
  8. 08Python Sets
  9. 09Python Dictionaries
  10. 10Python Functions
  11. 11Python Modules
  12. 12Python OOPs
  13. 13Python Exception Handling
  14. 14Python File Handling
  15. 15Python Searching & Sorting
  16. 16Python Advanced Topics
  17. 17Python MySQL
  18. 18Python MongoDB & SQLite
  19. 19Python MCQ

Chapter 14

Python File Handling

7 topics · 1 sections · beginner-friendly study notes · Updated

Share with friends:WhatsAppTelegram

Embed on your site

Free for teachers, schools and blogs. Please keep the attribution link.

Preview

File handling lets programs read and write persistent data.

Python offers open() with modes, the with statement for safe cleanup, and standard-library or third-party modules for CSV, JSON and Excel files.

Almost every real application stores or loads data: logs, reports, configuration and datasets.

Data cleaning, report generation, configuration files, API payloads and spreadsheets for business users.

1

Python File Handling

A file object is obtained with open(path, mode, encoding=...). Modes: r read (default), w write (truncate/create), a append, x exclusive create, + read and write, b binary, t text (default). Methods include read(), readline(), readlines(), write(), writelines(), seek(), tell() and close().

In short: Open the file, read or write, close it. Use with so closing is automatic.

Program ↔ File on disk

Think about it

File modes and read methods are tested in practical exams every year. Writing a log file with "a" mode, reading a text report line by line.

Always pass encoding="utf-8" for text files to avoid platform differences.

Iterating for line in f reads lazily one line at a time and is memory-friendly for large files, while read() loads everything.

"w" erases existing content immediately; use "a" to keep it.

Text mode translates newlines; binary mode ("rb", "wb") works with bytes for images and PDFs.

seek(offset) moves the cursor and tell() reports it.

pathlib.

Path provides an object-oriented API: Path("a.

txt").

exists(), read_text(), write_text().

Missing files raise FileNotFoundError; permission problems raise PermissionError.

Use os.

remove or Path.

unlink to delete a file.

Key points

  • Mode: String that decides how the file is opened.
  • File pointer: Current read/write position inside the file.
  • Encoding: Mapping from characters to bytes, e.g. UTF-8.
  • Binary mode: Reads and writes raw bytes.

Example

Code
from pathlib import Path
import os

with open("notes.txt", "w", encoding="utf-8") as f:    # create / overwrite
    f.write("line1\n")
    f.writelines(["line2\n", "line3\n"])

with open("notes.txt", "r", encoding="utf-8") as f:
    print(f.read())                                    # whole file

with open("notes.txt", encoding="utf-8") as f:
    for line in f:                                     # lazy, one line at a time
        print(line.rstrip())

with open("notes.txt", "a", encoding="utf-8") as f:    # append keeps old text
    f.write("line4\n")

with open("notes.txt", encoding="utf-8") as f:
    print(f.readline().strip())                        # line1
    print(f.tell())                                    # position after line1
    f.seek(0)
    print(len(f.readlines()))                          # 4

with open("data.bin", "wb") as f:                      # binary
    f.write(bytes([72, 105, 33]))
with open("data.bin", "rb") as f:
    print(f.read())                                    # b'Hi!'

p = Path("notes.txt")
print(p.exists(), p.stat().st_size > 0)                # True True
print(p.read_text(encoding="utf-8").count("line"))     # 4

os.remove("notes.txt")
os.remove("data.bin")
print(Path("notes.txt").exists())                      # False
2

Context Manager in Python

A context manager defines set-up and tear-down around a block of code used with the with statement. The object implements __enter__() (runs on entry, its return value is bound by as) and __exit__(exc_type, exc, tb) (runs on exit, even after an exception). contextlib.contextmanager builds one from a generator.

In short: with is a built-in "do the cleanup for me" promise.

with: open → use → auto close

Think about it

The with statement is the idiomatic way to manage resources and a recurring interview topic. A timer context manager, a database transaction that commits or rolls back automatically, temporary directories that clean themselves.

with open(...

) as f is equivalent to try/finally with f.

close().

__exit__ receives exception details; returning True suppresses the exception, returning False/None lets it propagate.

You can combine several managers: with open(a) as src, open(b, "w") as dst.

The decorator @contextmanager lets you write a generator that does set-up, yields the resource, and does tear-down in a finally block - much shorter than a class.

Standard managers: open, threading.

Lock, tempfile.

TemporaryDirectory, decimal.

localcontext, unittest.

mock.

patch, sqlite3 connections (transaction scope), contextlib.

suppress and contextlib.

redirect_stdout.

Key points

  • __enter__: Called at the start of with; returns the as value.
  • __exit__: Called at the end; may suppress exceptions.
  • @contextmanager: Turns a generator into a context manager.

Example

Code
import time
from contextlib import contextmanager

class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self
    def __exit__(self, exc_type, exc, tb):
        self.elapsed = time.perf_counter() - self.start
        return False                                   # do not hide exceptions

with Timer() as t:
    total = sum(range(100000))
print(f"took {t.elapsed:.4f}s, total={total}")

@contextmanager
def opened(path, mode="r"):
    f = open(path, mode, encoding="utf-8")
    try:
        yield f                                        # body of the with block runs here
    finally:
        f.close()
        print("closed", path)

with opened("demo.txt", "w") as f:
    f.write("hello")
with opened("demo.txt") as f:
    print(f.read())                                    # hello

class Swallow:
    def __enter__(self): return self
    def __exit__(self, exc_type, exc, tb):
        print("suppressing", exc_type.__name__)
        return True                                    # exception swallowed

with Swallow():
    1 / 0
print("program continues")

with open("demo.txt", encoding="utf-8") as src, open("copy.txt", "w", encoding="utf-8") as dst:
    dst.write(src.read().upper())                      # two managers at once

import os
os.remove("demo.txt"); os.remove("copy.txt")
3

Python Read CSV File

CSV (comma-separated values) is a plain-text table format. The csv module reads it with csv.reader (each row is a list of strings) or csv.DictReader (each row is a dict keyed by the header). Open files with newline="" so the module controls line endings.

In short: Each line is a row; commas separate columns. csv turns lines into Python lists or dicts for you.

Think about it

CSV parsing with DictReader is a favourite lab and interview program. Loading an exported bank statement or marks sheet into Python for calculation.

Never split by "," yourself: fields may contain quoted commas such as "Raj, Jr".

All values come back as strings, so convert with int() or float().

reader has a line_num attribute and supports other delimiters via delimiter=";" or a tab character.

next(reader) pulls off the header row.

DictReader exposes fieldnames and is more readable.

For very large files iterate row by row; for analysis use pandas.

read_csv, which handles types, missing values and big data.

csv.

Sniffer can guess the dialect.

io.

StringIO lets you parse CSV text that is already in memory.

Key points

  • csv.reader: Iterator of rows as lists.
  • csv.DictReader: Iterator of rows as dicts using header names.
  • Delimiter: Character that separates fields.
  • newline="": Required open() argument for correct CSV handling.

Example

Code
import csv, io, os

with open("students.csv", "w", newline="", encoding="utf-8") as f:   # create sample data
    csv.writer(f).writerows([["name", "marks"], ["Ana", "72"], ["Raj, Jr", "35"], ["Lin", "90"]])

with open("students.csv", newline="", encoding="utf-8") as f:
    reader = csv.reader(f)
    header = next(reader)
    print(header)                                    # ['name', 'marks']
    for row in reader:
        print(row)                                   # ['Raj, Jr', '35'] stays one field

with open("students.csv", newline="", encoding="utf-8") as f:
    total = 0
    for rec in csv.DictReader(f):
        print(rec["name"], int(rec["marks"]))        # convert to int yourself
        total += int(rec["marks"])
    print("average:", round(total / 3, 2))           # 65.67

text = "id;city\n1;Pune\n2;Delhi\n"
for row in csv.DictReader(io.StringIO(text), delimiter=";"):
    print(dict(row))                                 # {'id': '1', 'city': 'Pune'}

# pandas alternative (pip install pandas)
# import pandas as pd
# df = pd.read_csv("students.csv"); print(df["marks"].mean())

os.remove("students.csv")
4

Python Write CSV File

csv.writer(file).writerow(list) and .writerows(list_of_lists) write rows; csv.DictWriter(file, fieldnames).writeheader() and .writerow(dict) write dictionaries. Use newline="" with open(), and mode "a" to append.

In short: Hand Python your rows and it adds commas, quotes and line endings correctly.

Think about it

Report generation commonly ends with writing a CSV. Exporting daily sales totals to a file that Excel opens.

The writer quotes fields that contain the delimiter, quote character or newline, using QUOTE_MINIMAL by default; change this with quoting=csv.

QUOTE_ALL or QUOTE_NONNUMERIC.

DictWriter needs fieldnames and fills missing keys with restval; extra keys raise ValueError unless extrasaction="ignore".

When appending, write the header only if the file is new.

Numbers are written using str().

For analytic data frames use DataFrame.

to_csv(index=False).

Always write with encoding="utf-8" (or "utf-8-sig" for Excel on Windows to show special characters correctly).

Key points

  • writerow / writerows: Write one / many rows.
  • DictWriter: Writes dictionaries using fieldnames.
  • QUOTE_ALL: Quote every field.
  • utf-8-sig: UTF-8 with BOM so Excel detects encoding.

Example

Code
import csv, os

rows = [
    {"name": "Ana", "marks": 72},
    {"name": "Raj, Jr", "marks": 35},                  # comma inside value
]

with open("out.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=["name", "marks"])
    w.writeheader()
    w.writerows(rows)

with open("out.csv", encoding="utf-8") as f:
    print(f.read())
# name,marks
# Ana,72
# "Raj, Jr",35

with open("out.csv", "a", newline="", encoding="utf-8") as f:   # append, no header
    csv.writer(f).writerow(["Lin", 90])

with open("out.csv", newline="", encoding="utf-8") as f:
    print(len(list(csv.reader(f))) - 1, "data rows")             # 3

with open("pipe.csv", "w", newline="", encoding="utf-8") as f:
    w = csv.writer(f, delimiter="|", quoting=csv.QUOTE_ALL)
    w.writerow(["a", 1])
    w.writerow(["b", 2])
print(open("pipe.csv", encoding="utf-8").read())                # "a"|"1"  and  "b"|"2"

os.remove("out.csv"); os.remove("pipe.csv")
5

Python JSON

JSON (JavaScript Object Notation) is a lightweight text format for structured data. The json module converts between JSON text and Python objects: dumps()/loads() work with strings, dump()/load() work with files. Mapping: object <-> dict, array <-> list, string <-> str, number <-> int/float, true/false <-> True/False, null <-> None.

In short: JSON is the universal language of web APIs; json.dumps writes it, json.loads reads it.

File data ↔ Python objects

Think about it

JSON is everywhere: configs, REST APIs and NoSQL databases. Saving app settings, calling a weather API and parsing its response.

Serialisation (Python -> JSON) with indent=2 and sort_keys=True gives readable output; ensure_ascii=False keeps non-English characters.

Tuples become arrays and come back as lists; dict keys are always converted to strings, so {1: "a"} returns {"1": "a"}.

Objects that JSON cannot represent (datetime, set, custom class) raise TypeError unless you pass default=str or a custom function.

Invalid text raises json.

JSONDecodeError (a ValueError subclass).

Use json.

load(f) to read a file and json.

dump(obj, f, indent=2) to write one.

pickle is a Python-only binary alternative that is not safe for untrusted data.

Key points

  • Serialisation: Converting objects to text/bytes.
  • dumps / loads: To / from a string.
  • dump / load: To / from a file object.
  • JSONDecodeError: Raised for malformed JSON text.

Example

Code
import json, os
from datetime import datetime

data = {"name": "Ana", "scores": [90, 85], "active": True, "address": None, "pair": (1, 2)}

text = json.dumps(data, indent=2, sort_keys=True)
print(text)                                          # true / null / arrays in JSON syntax

back = json.loads(text)
print(back["scores"][0], back["active"], back["pair"])   # 90 True [1, 2]

with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2)
with open("data.json", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded["name"])                                # Ana

print(json.dumps({1: "a"}))                          # {"1": "a"}  keys become strings

print(json.dumps({"when": datetime(2025, 1, 15)}, default=str))
# {"when": "2025-01-15 00:00:00"}

try:
    json.loads("{bad json}")
except json.JSONDecodeError as e:
    print("Invalid JSON:", e.msg)                    # Expecting property name enclosed in double quotes

print(json.loads('{"a": 1.5, "b": [true, null]}'))   # {'a': 1.5, 'b': [True, None]}
os.remove("data.json")
6

Read Excel File

Excel (.xlsx) files are read in Python with openpyxl (low-level, cell access) or pandas.read_excel (tabular, data-science). Both need installation: pip install openpyxl pandas.

In short: Open the workbook, pick a sheet, loop over rows or load it into a DataFrame.

Think about it

Business data lives in spreadsheets, so reading them is a daily task for analysts. Importing a teacher marks sheet and computing class averages.

With openpyxl: load_workbook(path, data_only=True) returns a Workbook; wb.

sheetnames lists sheets; ws["A2"].

value reads a cell; ws.

iter_rows(min_row=2, values_only=True) yields tuples of values; ws.

max_row and ws.

max_column give the used range.

data_only=True returns the cached results of formulas instead of formula text (only available if Excel saved the file after calculating).

With pandas: pd.

read_excel("f.

xlsx", sheet_name="Marks", usecols="A:B", header=0) returns a DataFrame; pass sheet_name=None to read all sheets into a dict.

Old .

xls files need the xlrd package.

Always close or release large workbooks (wb.

close()) in read-only mode.

Key points

  • Workbook / Worksheet: The file / one sheet inside it.
  • iter_rows: Row iterator in openpyxl.
  • data_only: Read cached formula results instead of formulas.
  • DataFrame: pandas table object.

Example

Code
# pip install openpyxl pandas
from openpyxl import Workbook, load_workbook
import os

wb = Workbook()                                        # create a sample file first
ws = wb.active
ws.title = "Marks"
ws.append(["name", "marks"])
ws.append(["Ana", 72])
ws.append(["Raj", 35])
wb.save("marks.xlsx")

wb = load_workbook("marks.xlsx", data_only=True)
print(wb.sheetnames)                                   # ['Marks']
ws = wb["Marks"]
print(ws["A2"].value, ws.max_row, ws.max_column)       # Ana 3 2

for name, marks in ws.iter_rows(min_row=2, values_only=True):
    print(name, marks)

total = sum(row[1] for row in ws.iter_rows(min_row=2, values_only=True))
print("average:", total / (ws.max_row - 1))            # 53.5

import pandas as pd
df = pd.read_excel("marks.xlsx", sheet_name="Marks")
print(df)
print(df["marks"].mean())                              # 53.5

os.remove("marks.xlsx")
7

Write Excel File

To create .xlsx files use openpyxl (Workbook, worksheets, cells, styles, formulas) or pandas (DataFrame.to_excel, ExcelWriter). Call save() or close the writer to flush the file to disk.

In short: Build a workbook in memory, fill cells or rows, then save it.

Think about it

Generating Excel reports is a common automation task. Nightly script that exports sales numbers to an Excel report for managers.

openpyxl: ws.

append(list) adds a row, ws["B2"] = value sets a cell, ws.

cell(row=1, column=2, value=...

) uses numeric positions.

Formulas are stored as strings starting with "=" such as "=SUM(B2:B4)"; Excel calculates them when the file is opened (openpyxl itself does not calculate).

Styling uses openpyxl.

styles Font, PatternFill, Alignment; ws.

column_dimensions["A"].

width controls width; ws.

freeze_panes = "A2" freezes the header.

pandas: df.

to_excel("f.

xlsx", sheet_name="Data", index=False); for several sheets use with pd.

ExcelWriter("f.

xlsx") as writer: df1.

to_excel(writer, sheet_name="A").

Overwriting an existing file replaces it, so back up first.

Key points

  • ws.append: Adds a row after the last used row.
  • ExcelWriter: pandas helper to write multiple sheets to one file.
  • freeze_panes: Keeps header rows visible while scrolling.

Example

Code
# pip install openpyxl pandas
from openpyxl import Workbook, load_workbook
from openpyxl.styles import Font
import pandas as pd
import os

wb = Workbook()
ws = wb.active
ws.title = "Sales"
ws.append(["item", "qty", "price"])
for row in [("pen", 10, 5), ("book", 3, 120), ("bag", 1, 650)]:
    ws.append(row)

ws["E1"] = "total"
ws["E2"] = "=SUMPRODUCT(B2:B4, C2:C4)"                 # formula stored as text
for cell in ws[1]:
    cell.font = Font(bold=True)                         # bold header
ws.column_dimensions["A"].width = 16
ws.freeze_panes = "A2"
wb.save("sales.xlsx")

check = load_workbook("sales.xlsx")
print(check["Sales"]["E2"].value)                       # =SUMPRODUCT(B2:B4, C2:C4)
print(check["Sales"].max_row)                           # 4

df1 = pd.DataFrame({"name": ["Ana", "Raj"], "marks": [72, 35]})
df2 = pd.DataFrame({"city": ["Pune", "Delhi"]})
with pd.ExcelWriter("report.xlsx") as writer:           # two sheets in one file
    df1.to_excel(writer, sheet_name="Marks", index=False)
    df2.to_excel(writer, sheet_name="Cities", index=False)

print(pd.ExcelFile("report.xlsx").sheet_names)          # ['Marks', 'Cities']
os.remove("sales.xlsx"); os.remove("report.xlsx")

Solved examples

Example 01 · Basic

Count the number of lines in a text file named data.txt safely.

Given Data:
    Required To Find:

    Code

    Formula Applied:—
    Step-by-Step Solution:
    Step 1: Open with the with statement
    Step 2: Loop over the file object
    Step 3: Count with a sum or counter
    Final Answer: with open("data.txt", encoding="utf-8") as f: count = sum(1 for _ in f) print(count)

    Approach note: Iterating the file is memory-efficient compared with readlines().

    Example 02 · Intermediate

    Read students.csv with columns name,marks and print the name with the highest marks.

    Given Data:
      Required To Find:

      Code

      Formula Applied:—
      Step-by-Step Solution:
      Step 1: Open with newline=""
      Step 2: Use csv.DictReader
      Step 3: Pick the maximum by int(row["marks"])
      Final Answer: import csv with open("students.csv", newline="", encoding="utf-8") as f: rows = list(csv.DictReader(f)) top = max(rows, key=lambda r: int(r["marks"])) print(top["name"])

      Approach note: CSV values are strings; convert before comparing.

      Example 03 · Basic

      What is the result of json.dumps({"a": (1, 2), "b": None})?

      Given Data:
        Required To Find:

        Output string

        Formula Applied:—
        Step-by-Step Solution:
        Step 1: Tuple becomes an array
        Step 2: None becomes null
        Final Answer: {"a": [1, 2], "b": null}

        Approach note: Remember tuple -> array, None -> null, True -> true.

        Example 04 · Basic

        Using a with-block, write the three lines "A", "B", "C" to notes.txt then read them back as a list of lines without trailing newlines.

        Given Data:
          Required To Find:

          Code sketch and result

          Formula Applied:—
          Step-by-Step Solution:
          Step 1: Open for write and write each line with a newline
          Step 2: Open for read and strip each line
          Step 3: Result list is ["A", "B", "C"]
          Final Answer: with open("notes.txt","w") as f: f.write("A\nB\nC\n") with open("notes.txt") as f: lines = [ln.strip() for ln in f] # lines == ["A", "B", "C"]

          Approach note: with closes the file even if an error occurs.

          Real-world applications

          Python

          Using Python File Handling in real projects

          Data cleaning, report generation, configuration files, API payloads and spreadsheets for business users.

          Mechanism: Write small programs, read errors carefully, then grow complexity only after the basics are solid.

          Common mistakes

          ❌ Myth: Opening a file with "w" appends text.

          Why this is wrong: "w" truncates the file immediately.

          ✅ Verified Truth: Use "a" to append.

          ⚠️ Exam Tip: Use x to avoid accidental overwrites.

          ❌ Myth: CSV values come back as numbers.

          Why this is wrong: The csv module always returns strings.

          ✅ Verified Truth: Convert with int() or float().

          ⚠️ Exam Tip: pandas infers types for you.

          ❌ Myth: I must call f.close() manually.

          Why this is wrong: with closes automatically, even on errors.

          ✅ Verified Truth: Prefer with open(...).

          ⚠️ Exam Tip: Mention try/finally equivalence.

          Revision notes

          File handling lets programs read and write persistent data. Python offers open() with modes, the with statement for safe cleanup, and standard-library or third-party modules for CSV, JSON and Excel files.

          High-Yield Quick Revision Points

          1. r, w, a, x, +, b, t are the file mode letters.
          2. with open(...) closes the file automatically.
          3. csv: use newline="", DictReader/DictWriter; values are strings.
          4. json: dumps/loads for strings, dump/load for files.
          5. Excel: openpyxl for cells and styles, pandas for DataFrames.

          Practice questions

          Question 1 · MCQ (Interview / semester)

          Which mode opens a file for appending?

          Question 2 · MCQ (Interview / semester)

          What does json.loads("[1, 2]") return?

          Question 3 · MCQ (Interview / semester)

          Which csv class returns each row as a dictionary?

          Question 4 · MCQ (Interview / semester)

          Which method returns all lines of a file as a list?

          Question 5 · MCQ (Interview / semester)

          Which library is commonly used to write .xlsx files?

          Question 6 · MCQ (Interview / semester)

          The method __exit__ of a context manager runs