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.
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).
| Operation | Meaning | Common API |
|---|---|---|
| Create / write | Store text or bytes | open(path, "w"), Path.write_text |
| Read | Load content | open(path, "r"), Path.read_text |
| Append | Add to the end | open(path, "a") |
| Binary I/O | Images, zip, raw bytes | open(path, "rb") / "wb" |
| Delete | Remove a file | Path.unlink, os.remove |
| Directories | Create / list folders | Path.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.
| Mode | Meaning |
|---|---|
"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
withstatement.
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(...), notf.open(...)). - The main built-in is
open. Related helpers:print(..., file=f),input()(reads stdin), andPathhelpers frompathlib(stdlib, not built-ins). - After
open, most work is done with **file object methods** (f.read,f.write, …) — see the next tables.
| Function | What it does | Example | Notes |
|---|---|---|---|
open(path, mode="r", encoding=None) | Open a file; returns a file object | open("a.txt", "r", encoding="utf-8") | Prefer inside with |
open(path, "w", encoding="utf-8") | Create / truncate for writing | open("out.txt", "w", encoding="utf-8") | Creates parent? No — folder must exist |
open(path, "a", encoding="utf-8") | Open for append | open("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 create | open("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 stdin | name = input("Name: ") | Not a disk file; strips trailing \n |
isinstance(f, io.IOBase) | Check if object is a stream | isinstance(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 byopen. - For large files prefer
for line in f:overf.read()/f.readlines().
| Method | What it does | Example | Result / notes |
|---|---|---|---|
f.read() | Read entire content | f.read() | One str (text) or bytes (binary) |
f.read(n) | Read up to n chars / bytes | f.read(10) | Shorter string/bytes near EOF |
f.readline() | Read next line | f.readline() | Includes \n; "" at EOF |
f.readlines() | Read all remaining lines | f.readlines() | List of lines (memory-heavy) |
for line in f: | Iterate lines lazily | for line in f: ... | Preferred for big text files |
list(f) | Same idea as readlines via iteration | list(f) | List of lines |
f.readable() | True if stream allows reading | f.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.writereturns 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.
| Method | What it does | Example | Result / notes |
|---|---|---|---|
f.write(s) | Write a string / bytes | f.write("hi\n") | Returns count written |
f.writelines(lines) | Write an iterable of lines | f.writelines(["a\n", "b\n"]) | Does not add separators for you |
f.flush() | Force buffer to OS | f.flush() | Useful before crash-prone work |
f.truncate(size=None) | Resize file | f.truncate(0) | Default: truncate at current position |
f.writable() | True if stream allows writing | f.writable() | True / False |
print(x, file=f) | Built-in writing helper | print("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/seekto move within a file (prefer binary mode for precise byte offsets). - With
with open, you rarely callclose()yourself — the context manager does it.
| Method | What it does | Example | Result / notes |
|---|---|---|---|
f.tell() | Current file position | f.tell() | Integer offset |
f.seek(offset, whence=0) | Move position | f.seek(0) | 0 start, 1 current, 2 end |
f.seekable() | True if random access allowed | f.seekable() | Some streams are not |
f.close() | Close the file | f.close() | Prefer with instead |
f.closed | Attribute: already closed? | f.closed | True after close |
f.name | Name / path used to open | f.name | Often a string path |
f.mode | Mode string | f.mode | e.g. "r", "wb" |
f.fileno() | Underlying OS file descriptor | f.fileno() | Advanced / low-level |
f.__enter__ / __exit__ | Context manager protocol | with open(...) as f: | Enables with |
Writing and appending patterns
"w"truncates or creates."a"appends and creates if missing.Path.write_textoverwrites; combine withread_textfor 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
pathlibis the modern object-oriented path API (Python 3.4+).- Join with
/:Path("data") / "file.txt". - Prefer
Pathfor new code;os.pathstill appears in older examples.
| Method | Purpose |
|---|---|
Path.cwd() | Current working directory |
exists / is_file / is_dir | Checks |
mkdir(parents=True, exist_ok=True) | Create folders |
read_text / write_text | Text helpers |
read_bytes / write_bytes | Binary helpers |
unlink(missing_ok=True) | Delete file |
iterdir / glob / rglob | List / 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
| Exception | Typical cause |
|---|---|
FileNotFoundError | Read path does not exist |
PermissionError | No access rights / locked file |
IsADirectoryError | Expected a file, got a folder |
UnicodeDecodeError | Wrong text encoding |
FileExistsError | "x" mode and file already exists |
Advanced — File Handling
seek and tell
tell()returns the current position;seek(offset, whence)moves it.- Whence:
0start,1current,2end (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.walkis 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
csvmodule — 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/rmtreehandle many filesystem jobs.copy2attempts 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.
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.
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()) 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 foverreadlines()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
FileNotFoundErrorwith a clear message instead of a raw traceback in user-facing tools.
Practice Programs List
- Create
students.txtwith five names and read it three ways (read,readlineloop,Path.read_text). - Append a timestamp line to
log.txtevery run. - Count lines, words, and characters in a file your program creates.
- Copy a text file and a binary blob; verify byte equality.
- Search for a word and print line numbers.
- Rename with
Path.rename/replace, then delete withunlink. - Create
data/2026/octoberand write a file inside it. - Use
rglob("*.txt")to list sizes under a folder tree you create. - Write an atomic save helper with a temp file +
os.replace. - Convert a simple CSV you create into a formatted
report.txt. - Demonstrate
"x"mode raisingFileExistsErroron the second run. - Stream-process a multi-megabyte file without
read()of the whole content. - Handle a missing file with a friendly message and a non-zero exit code.
- Compare
open+ pathlib helpers for the same write/read task.