File handling allows Python programs to read from and write to files on disk. Python provides built-in functions for this, with the open() function at the core.
| Mode | Name | Description |
|---|---|---|
"r" |
Read | Default. Read only. Error if file doesn't exist. |
"w" |
Write | Write only. Creates file if not exists. Truncates (erases) if exists. |
"a" |
Append | Write only. Creates if not exists. Appends to end if exists. |
"x" |
Create | Creates file. Error if file already exists. |
"r+" |
Read+Write | File must exist. Read and write. |
"w+" |
Write+Read | Creates/truncates file. Read and write. |
"a+" |
Append+Read | Creates if not exists. Append writes + read. |
"b" |
Binary | Add to any mode: "rb", "wb". For non-text files. |
"t" |
Text | Default mode (text). Add to any mode: "rt", "wt". |
# ── Method 1: Basic open/close (manual — not recommended) ──
file = open("sample.txt", "r")
content = file.read()
print(content)
file.close() # MUST close manually!
# ── Method 2: with statement (RECOMMENDED — auto-closes) ──
with open("sample.txt", "r") as f:
content = f.read()
print(content)
# File is automatically closed after the 'with' block
# ── Reading methods ──
# read() — read entire file as one string
with open("sample.txt", "r") as f:
content = f.read()
print(content)
print(f"Total characters: {len(content)}")
# read(n) — read n characters
with open("sample.txt", "r") as f:
first_100 = f.read(100) # read first 100 characters
# readline() — read ONE line at a time
with open("sample.txt", "r") as f:
line1 = f.readline() # "Hello, World!\n"
line2 = f.readline() # "This is line 2\n"
print(line1.strip()) # remove newline
print(line2.strip())
# readlines() — read ALL lines into a list
with open("sample.txt", "r") as f:
lines = f.readlines() # ["line1\n", "line2\n", ...]
for line in lines:
print(line.strip())
# Iterate line by line (most memory-efficient — doesn't load whole file)
with open("sample.txt", "r") as f:
for line in f: # file object is iterable!
print(line.strip())
# ── File cursor / seek / tell ──
with open("sample.txt", "r") as f:
print(f.tell()) # 0 — cursor at start
chunk1 = f.read(10)
print(f.tell()) # 10 — cursor moved
f.seek(0) # go back to start
chunk2 = f.read(10) # same 10 characters
print(chunk1 == chunk2) # True
f.seek(0, 2) # seek to end (0 = 2nd arg means from end)
print(f.tell()) # file size in bytes
# ── Reading with encoding ──
with open("sample.txt", "r", encoding="utf-8") as f:
content = f.read()
# ── Check if file exists before reading ──
import os
filename = "sample.txt"
if os.path.exists(filename):
with open(filename, "r") as f:
print(f.read())
else:
print(f"File '{filename}' not found")
# Or use exception handling (more Pythonic):
try:
with open(filename, "r") as f:
print(f.read())
except FileNotFoundError:
print(f"File '{filename}' not found")
# ── Reading large files efficiently ──
def process_large_file(filename, chunk_size=1024):
"""Read file in chunks to avoid loading entire file into memory."""
with open(filename, "rb") as f: # binary mode for chunks
while True:
chunk = f.read(chunk_size)
if not chunk:
break
# process chunk
print(f"Processing {len(chunk)} bytes")
# ── Working with CSV files ──
import csv
# Read CSV
with open("data.csv", "r", newline="") as f:
reader = csv.reader(f)
header = next(reader) # skip header row
for row in reader:
print(row) # row is a list: ['Alice', '25', 'Chennai']
# Read as dict (header becomes keys)
with open("data.csv", "r") as f:
dict_reader = csv.DictReader(f)
for row in dict_reader:
print(row) # {'name': 'Alice', 'age': '25', 'city': 'Chennai'}
# ── Get file metadata ──
import os
info = os.stat("sample.txt")
print(f"Size: {info.st_size} bytes")
print(f"Modified: {info.st_mtime}")
from datetime import datetime
print(f"Modified: {datetime.fromtimestamp(info.st_mtime)}")# ── Write (creates file or OVERWRITES existing) ──
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
f.write("Second line\n")
f.write("Third line\n")
# write() returns number of characters written
with open("output.txt", "w") as f:
chars_written = f.write("Hello!")
print(f"Wrote {chars_written} characters") # 6
# writelines() — write a list of strings (no auto newline!)
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
# ── Append (adds to end without erasing) ──
with open("log.txt", "a") as f:
f.write("2024-01-15: Server started\n")
with open("log.txt", "a") as f:
f.write("2024-01-15: User logged in\n")
# ── Create (error if exists) ──
try:
with open("newfile.txt", "x") as f:
f.write("This is a new file\n")
except FileExistsError:
print("File already exists!")
# ── Write with print() ──
with open("output.txt", "w") as f:
print("Hello from print!", file=f) # print to file
print("Second line", file=f, end="\n")
# ── Write with encoding ──
with open("unicode.txt", "w", encoding="utf-8") as f:
f.write("Tamil: தமிழ்\n")
f.write("Hindi: हिन्दी\n")
f.write("Emoji: 🐍\n")
# ── Write binary data ──
with open("image_copy.jpg", "wb") as f:
with open("original.jpg", "rb") as src:
f.write(src.read())
# Or more efficiently:
import shutil
shutil.copy("original.jpg", "image_copy.jpg")
# ── Write JSON ──
import json
data = {"name": "Logesh", "age": 25, "skills": ["Python", "JS"]}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=4, ensure_ascii=False)
# ── Write CSV ──
import csv
employees = [
{"name": "Alice", "age": 25, "dept": "Engineering"},
{"name": "Bob", "age": 30, "dept": "Marketing"},
]
with open("employees.csv", "w", newline="", encoding="utf-8") as f:
fieldnames = ["name", "age", "dept"]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(employees)
# ── Atomic write (safe replacement) ──
import tempfile, os, shutil
def safe_write(filename, content):
"""Write to temp file, then atomically replace target."""
dir_name = os.path.dirname(os.path.abspath(filename))
with tempfile.NamedTemporaryFile(mode='w', dir=dir_name,
delete=False, suffix='.tmp') as tmp:
tmp.write(content)
tmp_name = tmp.name
shutil.move(tmp_name, filename) # atomic on most systems
safe_write("config.txt", "server=localhost\nport=8080\n")import os
import shutil
# ── Delete a single file ──
if os.path.exists("old_file.txt"):
os.remove("old_file.txt")
print("File deleted")
else:
print("File doesn't exist")
# With exception handling (more Pythonic)
try:
os.remove("old_file.txt")
print("Deleted successfully")
except FileNotFoundError:
print("File not found")
except PermissionError:
print("Permission denied")
# ── Delete an empty directory ──
try:
os.rmdir("empty_folder")
except FileNotFoundError:
print("Directory not found")
except OSError:
print("Directory is not empty — use shutil.rmtree()")
# ── Delete a directory and ALL its contents (DANGER!) ──
shutil.rmtree("folder_with_stuff", ignore_errors=True)
# ignore_errors=True — don't raise if dir doesn't exist
# ── Safe delete with backup (move to trash concept) ──
import shutil
def safe_delete(filepath, backup_dir="./trash"):
"""Move file to trash instead of permanent deletion."""
os.makedirs(backup_dir, exist_ok=True)
filename = os.path.basename(filepath)
backup_path = os.path.join(backup_dir, filename)
shutil.move(filepath, backup_path)
print(f"Moved '{filepath}' to '{backup_path}'")
# ── Rename / Move files ──
os.rename("old_name.txt", "new_name.txt") # rename
shutil.move("file.txt", "new_folder/file.txt") # move to folder
shutil.move("file.txt", "new_folder/new_name.txt") # move and rename
# ── Copy files ──
shutil.copy("source.txt", "destination.txt") # copy file
shutil.copy2("source.txt", "destination.txt") # copy with metadata
shutil.copytree("src_folder", "dst_folder") # copy entire folder
# ── Working with paths (pathlib — Modern Python 3.4+) ──
from pathlib import Path
# Create path object
p = Path("documents/report.txt")
home = Path.home() # user's home directory
cwd = Path.cwd() # current working directory
desktop = Path.home() / "Desktop" / "file.txt" # / operator joins paths!
# Path operations
print(p.name) # "report.txt"
print(p.stem) # "report"
print(p.suffix) # ".txt"
print(p.parent) # "documents"
print(p.parts) # ('documents', 'report.txt')
p.parent.mkdir(parents=True, exist_ok=True) # create parent dirs
p.write_text("Hello from pathlib!") # write text
print(p.read_text()) # read text
print(p.stat().st_size) # file size
p.unlink() # delete file (like os.remove)
p.rename("new_name.txt") # rename
# Check
print(p.exists()) # True/False
print(p.is_file()) # True if file
print(p.is_dir()) # True if directory
# Glob — find files by pattern
for py_file in Path(".").glob("*.py"):
print(py_file)
for any_file in Path(".").rglob("*.py"): # recursive
print(any_file)
# ── Temporary files ──
import tempfile
with tempfile.TemporaryFile(mode='w+') as tmp:
tmp.write("Temporary data\n")
tmp.seek(0)
print(tmp.read()) # auto-deleted after 'with' block
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as tmp:
tmp.write("Named temp file")
print(f"Temp file: {tmp.name}")"""Student record management using file handling."""
import json
import os
from pathlib import Path
RECORDS_FILE = Path("students.json")
def load_records():
if not RECORDS_FILE.exists():
return []
try:
return json.loads(RECORDS_FILE.read_text(encoding="utf-8"))
except (json.JSONDecodeError, IOError):
return []
def save_records(records):
RECORDS_FILE.write_text(
json.dumps(records, indent=4, ensure_ascii=False),
encoding="utf-8"
)
def add_student(name, grade, score):
records = load_records()
records.append({"name": name, "grade": grade, "score": score})
save_records(records)
print(f"Added: {name}")
def list_students():
records = load_records()
if not records:
print("No students found")
return
for i, s in enumerate(records, 1):
print(f"{i}. {s['name']} — Grade {s['grade']}: {s['score']}")
def delete_student(name):
records = load_records()
filtered = [s for s in records if s["name"] != name]
if len(filtered) == len(records):
print(f"Student '{name}' not found")
else:
save_records(filtered)
print(f"Deleted: {name}")
# Demo
add_student("Alice", "A", 92)
add_student("Bob", "B", 78)
add_student("Charlie", "A+", 98)
list_students()
delete_student("Bob")
list_students()Q: Why should you use with open() instead of open() + close()?
A: The
withstatement uses a context manager that guarantees the file is closed when the block exits, even if an exception occurs. With manualfile.close(), if an exception happens before the close call, the file remains open — causing resource leaks.
Q: What is the difference between "w" and "a" mode?
A:
"w"(write) truncates the file — it erases all existing content and starts fresh."a"(append) preserves existing content and writes new data at the end. Use"a"for log files; use"w"when you want to completely replace file contents.
Q: What is the difference between read(), readline(), and readlines()?
A:
read()reads the entire file as one string.readline()reads one line at a time.readlines()reads all lines into a list. For large files, iterate withfor line in file:— it's the most memory-efficient as it processes one line at a time without loading everything into memory.
Q: What is pathlib and why is it preferred over os.path?
A:
pathlib.Path(Python 3.4+) provides an object-oriented interface for file paths. It's more readable (path / "subdir" / "file.txt"vsos.path.join(...)), has convenient methods (read_text(),write_text(),glob()), and handles OS differences automatically.
| Mode | Creates? | Truncates? | Read? | Write? |
|---|---|---|---|---|
"r" |
❌ | ❌ | ✅ | ❌ |
"w" |
✅ | ✅ | ❌ | ✅ |
"a" |
✅ | ❌ | ❌ | ✅ (end) |
"x" |
✅ (or fail) | — | ❌ | ✅ |
"r+" |
❌ | ❌ | ✅ | ✅ |
| Concept | Key Point |
|---|---|
with open() |
Always use — auto-closes |
f.read() |
Entire file as string |
f.readline() |
One line |
f.readlines() |
All lines as list |
for line in f |
Memory-efficient iteration |
f.write(s) |
Write string |
f.writelines(lst) |
Write list of strings |
os.remove(path) |
Delete file |
shutil.rmtree(dir) |
Delete directory + contents |
pathlib.Path |
Modern path handling |