Skip to main content

Modules & Files

File Handling

Complete lesson for File Handling using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — File Handling

Section: Modules & Files. File handling in Python — create, read, write, append, built-in open and file methods, pathlib, and context managers.

What is file handling?

  • File handling means creating, reading, updating, and deleting files on disk from a program.
  • Variables live in RAM and disappear when the process ends; files provide persistence.
  • Real-life analogy: a notebook — open, read, write, append, tear out pages (delete), photocopy (copy).
OperationMeaningCommon API
Create / writeStore text or bytesopen(path, "w"), Path.write_text
ReadLoad contentopen(path, "r"), Path.read_text
AppendAdd to the endopen(path, "a")
Binary I/OImages, zip, raw bytesopen(path, "rb") / "wb"
DeleteRemove a filePath.unlink, os.remove
DirectoriesCreate / list foldersPath.mkdir, iterdir, rglob

File modes

  • Mode controls read/write and text/binary. Default is text "r".
  • Text modes apply encoding (use UTF-8 explicitly). Binary modes skip encoding.
ModeMeaning
"r"Read text (file must exist)
"w"Write text (create / truncate)
"a"Append text (create if missing)
"x"Exclusive create (fail if exists)
"r+"Read and write
"rb" / "wb" / "ab"Binary variants
"t"Text (default); often omitted

with open context manager

  • with open(...) as f: closes the file automatically — even on exceptions.
  • Prefer this over manual f.close().
  • You can open multiple files in one with statement.
from pathlib import Path

path = Path("demo_notes.txt")
path.write_text("first line\n", encoding="utf-8")

with open(path, "a", encoding="utf-8") as f:
    f.write("second line\n")

with open(path, "r", encoding="utf-8") as f:
    print(f.read())

Built-in functions for file handling

  • These are **built-in functions** (call as open(...), not f.open(...)).
  • The main built-in is open. Related helpers: print(..., file=f), input() (reads stdin), and Path helpers from pathlib (stdlib, not built-ins).
  • After open, most work is done with **file object methods** (f.read, f.write, …) — see the next tables.
FunctionWhat it doesExampleNotes
open(path, mode="r", encoding=None)Open a file; returns a file objectopen("a.txt", "r", encoding="utf-8")Prefer inside with
open(path, "w", encoding="utf-8")Create / truncate for writingopen("out.txt", "w", encoding="utf-8")Creates parent? No — folder must exist
open(path, "a", encoding="utf-8")Open for appendopen("log.txt", "a", encoding="utf-8")Creates file if missing
open(path, "rb") / "wb"Binary open (no encoding)open("img.png", "rb")Returns/accepts bytes
open(path, "x", encoding="utf-8")Exclusive createopen("new.txt", "x", encoding="utf-8")Raises if file exists
print(*args, file=f)Write a line to a file (or stdout)print("hi", file=f)Adds newline by default
input(prompt="")Read one line from stdinname = input("Name: ")Not a disk file; strips trailing \n
isinstance(f, io.IOBase)Check if object is a streamisinstance(f, io.TextIOBase)Needs import io
from pathlib import Path

p = Path("builtin_open_demo.txt")
with open(p, "w", encoding="utf-8") as f:
    print("line 1", file=f)
    print("line 2", file=f)

with open(p, "r", encoding="utf-8") as f:
    print(f.read())

File object methods — reading

  • Call as f.method(...) on the file object returned by open.
  • For large files prefer for line in f: over f.read() / f.readlines().
MethodWhat it doesExampleResult / notes
f.read()Read entire contentf.read()One str (text) or bytes (binary)
f.read(n)Read up to n chars / bytesf.read(10)Shorter string/bytes near EOF
f.readline()Read next linef.readline()Includes \n; "" at EOF
f.readlines()Read all remaining linesf.readlines()List of lines (memory-heavy)
for line in f:Iterate lines lazilyfor line in f: ...Preferred for big text files
list(f)Same idea as readlines via iterationlist(f)List of lines
f.readable()True if stream allows readingf.readable()True / False
from pathlib import Path

p = Path("lines_demo.txt")
p.write_text("alpha\nbeta\ngamma\n", encoding="utf-8")
with open(p, encoding="utf-8") as f:
    print(f.readline().strip())   # alpha
    print(f.read())               # beta\ngamma\n

File object methods — writing

  • "w" truncates existing content. "a" keeps old content and writes at the end.
  • write returns the number of characters / bytes written. It does **not** add a newline unless you include one.
  • print(..., file=f) is handy when you want automatic newlines.
MethodWhat it doesExampleResult / notes
f.write(s)Write a string / bytesf.write("hi\n")Returns count written
f.writelines(lines)Write an iterable of linesf.writelines(["a\n", "b\n"])Does not add separators for you
f.flush()Force buffer to OSf.flush()Useful before crash-prone work
f.truncate(size=None)Resize filef.truncate(0)Default: truncate at current position
f.writable()True if stream allows writingf.writable()True / False
print(x, file=f)Built-in writing helperprint("ok", file=f)Adds \n unless end= set
from pathlib import Path

log = Path("app.log")
log.write_text("start\n", encoding="utf-8")
with open(log, "a", encoding="utf-8") as f:
    f.write("event=login\n")
    print("event=logout", file=f)
print(log.read_text(encoding="utf-8"))

File object methods — position, close, and info

  • Use tell / seek to move within a file (prefer binary mode for precise byte offsets).
  • With with open, you rarely call close() yourself — the context manager does it.
MethodWhat it doesExampleResult / notes
f.tell()Current file positionf.tell()Integer offset
f.seek(offset, whence=0)Move positionf.seek(0)0 start, 1 current, 2 end
f.seekable()True if random access allowedf.seekable()Some streams are not
f.close()Close the filef.close()Prefer with instead
f.closedAttribute: already closed?f.closedTrue after close
f.nameName / path used to openf.nameOften a string path
f.modeMode stringf.modee.g. "r", "wb"
f.fileno()Underlying OS file descriptorf.fileno()Advanced / low-level
f.__enter__ / __exit__Context manager protocolwith open(...) as f:Enables with

Writing and appending patterns

  • "w" truncates or creates. "a" appends and creates if missing.
  • Path.write_text overwrites; combine with read_text for simple updates.
  • See the writing-methods table above for write / writelines / print.
from pathlib import Path

log = Path("append_demo.txt")
with open(log, "w", encoding="utf-8") as f:
    f.write("start\n")
with open(log, "a", encoding="utf-8") as f:
    f.write("more\n")
print(log.read_text(encoding="utf-8"))

pathlib.Path essentials

  • pathlib is the modern object-oriented path API (Python 3.4+).
  • Join with /: Path("data") / "file.txt".
  • Prefer Path for new code; os.path still appears in older examples.
MethodPurpose
Path.cwd()Current working directory
exists / is_file / is_dirChecks
mkdir(parents=True, exist_ok=True)Create folders
read_text / write_textText helpers
read_bytes / write_bytesBinary helpers
unlink(missing_ok=True)Delete file
iterdir / glob / rglobList / pattern search
resolve()Absolute normalized path

Encoding matters

  • Always pass encoding="utf-8" for text unless you know another encoding is required.
  • On Windows, the default encoding may not be UTF-8 depending on Python version/settings.
  • errors="replace" or "ignore" can soften decode failures for messy data — use carefully.

Binary files

  • Use "rb" / "wb" for non-text data (images, zip, protobuf).
  • No encoding argument in binary mode.
  • Copy efficiently with loops over chunks or shutil.copyfile.
from pathlib import Path

src = Path("blob.bin")
dst = Path("blob-copy.bin")
src.write_bytes(b"\x00\x01\x02\xffPYTHON")
dst.write_bytes(src.read_bytes())
print(dst.read_bytes())

Common exceptions

ExceptionTypical cause
FileNotFoundErrorRead path does not exist
PermissionErrorNo access rights / locked file
IsADirectoryErrorExpected a file, got a folder
UnicodeDecodeErrorWrong text encoding
FileExistsError"x" mode and file already exists
L2

Advanced — File Handling

seek and tell

  • tell() returns the current position; seek(offset, whence) moves it.
  • Whence: 0 start, 1 current, 2 end (binary-safe rules differ slightly for text).
from pathlib import Path

p = Path("seek_demo.txt")
p.write_text("ABCDEFGH", encoding="utf-8")
with open(p, "rb") as f:
    print(f.read(3))      # b'ABC'
    print(f.tell())       # 3
    f.seek(0)
    print(f.read(2))      # b'AB'
    f.seek(-2, 2)
    print(f.read())       # b'GH'

Directory walking

  • Path.rglob("*.py") finds files recursively.
  • os.walk is the classic tuple-based alternative.
  • For huge trees, prefer generators and avoid loading everything into a list.
from pathlib import Path

root = Path("walk_demo")
(root / "a").mkdir(parents=True, exist_ok=True)
(root / "a" / "one.txt").write_text("1", encoding="utf-8")
(root / "two.txt").write_text("2", encoding="utf-8")
for p in sorted(root.rglob("*.txt")):
    print(p.as_posix(), "->", p.read_text(encoding="utf-8"))

Atomic-ish write pattern

  • Write to a temporary file in the same directory, then replace the target.
  • Reduces the chance of leaving a half-written file if the process crashes.
from pathlib import Path
import os

def atomic_write(path: Path, text: str) -> None:
    tmp = path.with_suffix(path.suffix + ".tmp")
    tmp.write_text(text, encoding="utf-8")
    os.replace(tmp, path)

target = Path("settings.txt")
atomic_write(target, "theme=dark\n")
print(target.read_text(encoding="utf-8"))

CSV-style processing without the csv module focus

  • For real CSV, prefer the csv module — but understanding split/join helps interviews.
  • Always create the sample input inside the program so demos are self-contained.
from pathlib import Path

csv_path = Path("students.csv")
csv_path.write_text("name,marks\nAsha,91\nRavi,67\nMeena,78\n", encoding="utf-8")
rows = csv_path.read_text(encoding="utf-8").splitlines()
header, *body = rows
print("header:", header)
for line in body:
    name, marks = line.split(",")
    status = "PASS" if int(marks) >= 70 else "RETRY"
    print(f"{name:8} {marks} {status}")

shutil for copy/move

  • shutil.copy / copy2 / move / rmtree handle many filesystem jobs.
  • copy2 attempts to preserve metadata.
from pathlib import Path
import shutil

src = Path("original.txt")
src.write_text("payload\n", encoding="utf-8")
dst = Path("copied.txt")
shutil.copy2(src, dst)
print(dst.read_text(encoding="utf-8"))
shutil.move(str(dst), "copied-renamed.txt")
print(Path("copied-renamed.txt").exists())

Large files: stream, do not swallow

  • Avoid read() / read_text() for multi-GB logs.
  • Iterate line by line or read fixed-size chunks.
  • Same idea as Java Files.lines — keep a small working set.
L3

Tricky Interview Points

Q1) Why use with open as f?

Answer It guarantees the file is closed promptly via the context manager protocol, even if an exception occurs.

Q2) What is the main built-in for files?

Answer open(path, mode, encoding=...) returns a file object. Prefer using it inside a with statement. Reading/writing is done with methods like read and write.

Q3) Difference between f.write and print(..., file=f)?

Answer write sends exactly the string/bytes you pass (no automatic newline). print converts args to text, separates them, and adds a newline by default.

Q4) Difference between "w" and "a"?

Answer "w" truncates or creates; "a" appends at the end and creates if missing.

Q5) Text mode vs binary mode?

Answer Text mode works with str and applies encoding/newlines. Binary mode works with bytes and does not decode.

Q6) Why pass encoding="utf-8"?

Answer Defaults can differ by platform/settings. Explicit UTF-8 makes behavior portable.

Q7) pathlib vs os.path?

Answer pathlib provides object-oriented Path methods; os.path uses string functions. Prefer pathlib for new code.

Q8) How do you read a large file safely?

Answer Iterate for line in f or read chunks; avoid loading the entire file into memory.

Q9) What exception is raised when opening a missing file for read?

Answer FileNotFoundError (a subclass of OSError).

Q10) What does Path.write_text do if the file exists?

Answer It overwrites the entire file with the new string.

Q11) How do you delete a file with pathlib?

Answer Path.unlink(missing_ok=True) deletes it; missing_ok avoids FileNotFoundError if absent (Python 3.8+).

Q12) What is seek used for?

Answer Moving the file pointer to a byte/character position for random access reads or writes.

Q13) How do you copy a file?

Answer shutil.copy or copy2, or read/write bytes yourself. copy2 tries to preserve metadata.

Q14) Difference between read() and readline()?

Answer read() returns the whole remaining content (or n chars). readline() returns the next line only.

L4

Simple Programs

Create, write, read, append (self-contained)

from pathlib import Path

p = Path("notes.txt")
p.write_text("Line 1\n", encoding="utf-8")
with open(p, "a", encoding="utf-8") as f:
    f.write("Line 2\n")
    f.write("Line 3\n")
print(p.read_text(encoding="utf-8"))
print("size:", p.stat().st_size, "bytes")

Count lines, words, and characters

from pathlib import Path

p = Path("wc_input.txt")
p.write_text("Hello world\nPython files\nHello again\n", encoding="utf-8")

lines = words = chars = 0
with open(p, encoding="utf-8") as f:
    for line in f:
        lines += 1
        chars += len(line)
        parts = line.split()
        words += len(parts)
print(f"Lines={lines} Words={words} Chars={chars}")

Search a word and print line numbers

from pathlib import Path

p = Path("search_notes.txt")
p.write_text(
    "python is fun\n"
    "learn python daily\n"
    "java is also useful\n"
    "python file handling\n",
    encoding="utf-8",
)
needle = "python"
found = 0
for i, line in enumerate(p.read_text(encoding="utf-8").splitlines(), start=1):
    if needle in line.lower():
        print(f"Line {i}: {line}")
        found += 1
print(found, "matching line(s)")

CSV to report (creates sample CSV first)

from pathlib import Path

csv_path = Path("students.csv")
csv_path.write_text("name,marks\nAsha,91\nRavi,67\nMeena,78\n", encoding="utf-8")

report = Path("report.txt")
lines = csv_path.read_text(encoding="utf-8").splitlines()
with open(report, "w", encoding="utf-8") as out:
    out.write(f"{'Name':<8} {'Marks':>5} {'Result':>6}\n")
    for row in lines[1:]:
        name, marks_s = row.split(",")
        marks = int(marks_s)
        result = "PASS" if marks >= 70 else "RETRY"
        out.write(f"{name:<8} {marks:>5} {result:>6}\n")
print(report.read_text(encoding="utf-8"))

Binary copy with a byte buffer

from pathlib import Path

src = Path("photo.bin")
dst = Path("photo-copy.bin")
src.write_bytes(bytes(range(64)) + b"IMG")

with open(src, "rb") as inf, open(dst, "wb") as outf:
    while True:
        chunk = inf.read(16)
        if not chunk:
            break
        outf.write(chunk)
print("copied", dst.stat().st_size, "bytes; match=", src.read_bytes() == dst.read_bytes())

Merge two files into one

from pathlib import Path

part1 = Path("part1.txt")
part2 = Path("part2.txt")
part1.write_text("AAA\nBBB\n", encoding="utf-8")
part2.write_text("CCC\nDDD\n", encoding="utf-8")

merged = Path("merged.txt")
merged.write_text("", encoding="utf-8")
for name in (part1, part2):
    with open(merged, "a", encoding="utf-8") as out, open(name, encoding="utf-8") as inp:
        out.write(inp.read())
print(merged.read_text(encoding="utf-8"))
print("merged size:", merged.stat().st_size)

List files with sizes using pathlib

from pathlib import Path

root = Path("list_demo")
(root / "sub").mkdir(parents=True, exist_ok=True)
(root / "a.txt").write_text("aaaa", encoding="utf-8")
(root / "sub" / "b.txt").write_text("bbbbbb", encoding="utf-8")
(root / "c.log").write_text("log", encoding="utf-8")

for p in sorted(root.rglob("*")):
    if p.is_file():
        print(f"{p.stat().st_size:5}  {p.relative_to(root).as_posix()}")

Safe read with friendly error handling

from pathlib import Path

missing = Path("no_such_file_12345.txt")
try:
    print(missing.read_text(encoding="utf-8"))
except FileNotFoundError:
    print("Friendly message: file not found ->", missing.name)

ok = Path("exists_now.txt")
ok.write_text("present\n", encoding="utf-8")
print("read ok:", ok.read_text(encoding="utf-8").strip())
L5

Problem Solving Tricks

  • Always use with open(...) so files close automatically.
  • Pass encoding="utf-8" for text unless you truly need another encoding.
  • Prefer for line in f over readlines() for large files.
  • Use "a" to append; "w" will wipe the file.
  • Build paths with Path("dir") / "file.txt", not string slash hacks alone.
  • Create sample input inside demos so they run anywhere.
  • Path.unlink(missing_ok=True) avoids noisy errors when cleaning up.
  • Binary for bytes; text for str — do not mix casually.
  • print(..., file=f) is great for quick line writes.
  • Catch FileNotFoundError with a clear message instead of a raw traceback in user-facing tools.
L6

Practice Programs List

  1. Create students.txt with five names and read it three ways (read, readline loop, Path.read_text).
  2. Append a timestamp line to log.txt every run.
  3. Count lines, words, and characters in a file your program creates.
  4. Copy a text file and a binary blob; verify byte equality.
  5. Search for a word and print line numbers.
  6. Rename with Path.rename / replace, then delete with unlink.
  7. Create data/2026/october and write a file inside it.
  8. Use rglob("*.txt") to list sizes under a folder tree you create.
  9. Write an atomic save helper with a temp file + os.replace.
  10. Convert a simple CSV you create into a formatted report.txt.
  11. Demonstrate "x" mode raising FileExistsError on the second run.
  12. Stream-process a multi-megabyte file without read() of the whole content.
  13. Handle a missing file with a friendly message and a non-zero exit code.
  14. Compare open + pathlib helpers for the same write/read task.