⬅ Previous Next ➡

File Handling

File Operations (Basics)
  • File handling is used to store and read data permanently.
  • Main steps: openread/writeclose
  • Prefer with statement (auto closes file).
# Basic open and close
f = open("data.txt", "w")
f.write("Hello File")
f.close()
File Modes (Important)
  • "r" read (file must exist)
  • "w" write (creates new / overwrites existing)
  • "a" append (adds at end, creates if not exist)
  • "x" create (error if file exists)
  • "t" text mode (default)
  • "b" binary mode (images, pdf, etc.)
  • Common combos: "r+", "w+", "a+"
# examples
open("file.txt", "r")
open("file.txt", "w")
open("file.txt", "a")
open("img.png", "rb")
Reading Files (read, readline, readlines)
  • read() reads full content
  • readline() reads one line
  • readlines() reads all lines as a list
with open("data.txt", "r") as f:
    content = f.read()
    print(content)

with open("data.txt", "r") as f:
    line = f.readline()
    print(line)

with open("data.txt", "r") as f:
    lines = f.readlines()
    print(lines)
Writing Files (write, writelines)
  • write() writes a string
  • writelines() writes a list of strings
  • In write mode "w", old data is overwritten
with open("notes.txt", "w") as f:
    f.write("Line 1\n")
    f.write("Line 2\n")

lines = ["A\n", "B\n", "C\n"]
with open("letters.txt", "w") as f:
    f.writelines(lines)
Appending Files (a mode)
  • "a" adds new data at the end of file.
  • Creates file if it does not exist.
with open("log.txt", "a") as f:
    f.write("New log entry\n")
with Statement (Recommended)
  • with automatically closes the file after the block.
  • Prevents file resource leak and ensures safe handling.
with open("data.txt", "r") as f:
    print(f.read())

# no need to call f.close()
CSV Handling (Read CSV)
  • Use csv module for CSV files.
  • csv.reader reads rows as lists.
import csv

with open("students.csv", "r", newline="") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
CSV Handling (Write CSV)
  • csv.writer writes rows.
  • Use newline="" to avoid blank lines on Windows.
import csv

data = [
    ["Name", "Age"],
    ["Sourav", 25],
    ["Amit", 22]
]

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(data)
Check File Existence
  • Use os.path.exists() to check file availability.
  • Prevents errors while reading.
import os

filename = "data.txt"

if os.path.exists(filename):
    with open(filename, "r") as f:
        print(f.read())
else:
    print("File not found")
File Exceptions (try-except)
  • Use exceptions to handle file errors safely.
  • Common errors: FileNotFoundError, PermissionError.
try:
    with open("missing.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("File does not exist")
except PermissionError:
    print("Permission denied")
except Exception as e:
    print("Error:", e)
⬅ Previous Next ➡