LearningPython TutorialFile Handling
CHAPTER 15 · DATA PERSISTENCE

Python File Handling

Programs sirf memory me data process nahi karte; real applications ko text, reports, configuration aur records files me read/write bhi karne padte hain. Is chapter me safe file access, context managers, paths, encodings aur CSV basics practical way me samjhenge.

English + Hinglish68 min readOnline practice included

What is file handling?

File handling means program se file open karna, data read/write karna aur resource ko properly close karna. File system data process ke end ke baad bhi persist kar sakta hai, unlike ordinary variables jo program end hone par memory se chale jate hain.

Hinglish Explanation

Variable temporary notebook jaisa hai; file disk par saved notebook jaisi hai. Lekin exact persistence environment par depend karta hai — BrounStack Playground jaise sandbox me temporary files next run tak guaranteed nahi hote.

open() basics

open-file.pyPython
file = open("notes.txt", "r", encoding="utf-8")
content = file.read()
print(content)
file.close()

open() file object return karta hai. Manual close() possible hai, but normal application code me with statement safer and cleaner hai.

Common file modes

  • "r" — read; file missing ho to FileNotFoundError.
  • "w" — write; existing file truncate/overwrite ho sakti hai, missing file create hoti hai.
  • "a" — append; content end me add hota hai.
  • "x" — exclusive create; file already exist ho to FileExistsError.
  • "b" — binary modifier, e.g. "rb".
  • "t" — text mode; default behavior.
  • "+" — read and write capability combine karta hai; beginner code me only when genuinely needed.
Important: "w" mode existing content erase kar sakta hai. Production data par mode choose karte waqt deliberate raho.

Use with for automatic cleanup

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

# file automatically closed after the block

Context manager block exit hote hi file close kar deta hai, even when block ke andar exception ho. Isi reason se with preferred pattern hai.

Read a whole file

read.pyPython
with open("notes.txt", "r", encoding="utf-8") as file:
    text = file.read()

print(text)

read() complete remaining content string me deta hai. Very large files ke liye complete file memory me load karna unnecessary ho sakta hai.

readline() and readlines()

lines.pyPython
with open("notes.txt", "r", encoding="utf-8") as file:
    first_line = file.readline()
    remaining_lines = file.readlines()

print(first_line)
print(remaining_lines)

readline() one line read karta hai. readlines() remaining lines ki list return karta hai. Lines me newline character included ho sakta hai.

Iterate over a file line by line

iterate-file.pyPython
with open("marks.txt", "r", encoding="utf-8") as file:
    for line in file:
        value = line.strip()
        if value:
            print(value)

Line-by-line iteration large text files ke liye memory-friendly pattern hai because all lines ek saath list me load karna required nahi.

Write text to a file

write.pyPython
with open("report.txt", "w", encoding="utf-8") as file:
    file.write("Student Report\n")
    file.write("Average: 86.50\n")

write() string write karta hai and written character count return kar sakta hai. Newline automatically add nahi hoti; \n explicitly likhna padta hai.

writelines() does not add separators

writelines.pyPython
lines = ["HTML\n", "CSS\n", "Python\n"]

with open("skills.txt", "w", encoding="utf-8") as file:
    file.writelines(lines)

writelines() iterable of strings write karta hai, but newline automatically insert nahi karta. Strings me separators khud include karo.

Append without overwriting

append.pyPython
with open("activity.log", "a", encoding="utf-8") as file:
    file.write("User completed Chapter 15\n")

Append mode existing content preserve karke end par new data add karta hai. Logging-like simple workflows me useful hai.

File position and seek()

position.pyPython
with open("notes.txt", "r", encoding="utf-8") as file:
    print(file.read(5))
    print(file.tell())
    file.seek(0)
    print(file.read(5))

tell() current stream position batata hai. seek() position change karta hai. Text-mode seeking details encoding ke saath nuanced ho sakti hain, so beginner code me simple use cases tak raho.

Always think about text encoding

Text file bytes ko characters me convert karne ke liye encoding use hoti hai. Cross-platform projects me explicit encoding="utf-8" common and predictable choice hai.

unicode.pyPython
message = "Namaste — Python सीखना मज़ेदार है"

with open("message.txt", "w", encoding="utf-8") as file:
    file.write(message)

with open("message.txt", "r", encoding="utf-8") as file:
    print(file.read())

Wrong encoding choose karne par UnicodeDecodeError ya corrupted-looking text aa sakta hai.

Prefer pathlib for modern paths

pathlib.pyPython
from pathlib import Path

path = Path("data") / "notes.txt"
print(path)
print(path.name)
print(path.suffix)

pathlib.Path path joining aur common filesystem operations ko object-oriented, cross-platform style me express karta hai.

Path.read_text() and write_text()

path-shortcuts.pyPython
from pathlib import Path

path = Path("notes.txt")
path.write_text("Python file handling\nBrounStack", encoding="utf-8")
print(path.read_text(encoding="utf-8"))

Small text files ke liye these convenience methods concise hain. Large files me streaming/iteration more appropriate ho sakta hai.

Try temporary file example →

Check paths only when it helps the flow

exists.pyPython
from pathlib import Path

path = Path("notes.txt")

if path.exists() and path.is_file():
    print(path.read_text(encoding="utf-8"))
else:
    print("File not found")

Existence check useful hai, but race conditions possible hoti hain: check aur open ke beech file change ho sakti hai. Real code me expected OSError handle karna bhi important hai.

Create directories safely

directories.pyPython
from pathlib import Path

folder = Path("reports")
folder.mkdir(parents=True, exist_ok=True)

file_path = folder / "summary.txt"
file_path.write_text("Report ready", encoding="utf-8")

parents=True missing parent directories create kar sakta hai; exist_ok=True existing directory ko normal case treat karta hai.

Handle filesystem errors

file-errors.pyPython
from pathlib import Path

path = Path("missing.txt")

try:
    text = path.read_text(encoding="utf-8")
except FileNotFoundError:
    print("File does not exist")
except PermissionError:
    print("Permission denied")
except OSError as error:
    print("File system error:", error)
else:
    print(text)

OSError filesystem-related exceptions ka common parent hai. Specific expected errors pehle catch karo, broader handler baad me.

Relative vs absolute paths

Path("notes.txt") relative path hai and current working directory se resolve hota hai. Absolute path full location represent karta hai. Wrong working directory common beginner confusion hai.

resolve.pyPython
from pathlib import Path

path = Path("notes.txt")
print(path.resolve())
Security note: Untrusted user input ko blindly file path me use mat karo. Path traversal jaise ../../secret.txt patterns sensitive files expose ya overwrite kar sakte hain.

CSV basics with the csv module

CSV simple tabular text format hai. Commas ko manually split() karna quoted commas and escaping ke cases me wrong ho sakta hai; Python ka csv module better hai.

csv-read.pyPython
import csv

with open("students.csv", "r", encoding="utf-8", newline="") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row["name"], row["score"])

DictReader header names ko keys banata hai. CSV files ke saath newline="" use karna recommended pattern hai.

Write CSV data

csv-write.pyPython
import csv

rows = [
    {"name": "Aman", "score": 88},
    {"name": "Riya", "score": 92},
]

with open("students.csv", "w", encoding="utf-8", newline="") as file:
    writer = csv.DictWriter(file, fieldnames=["name", "score"])
    writer.writeheader()
    writer.writerows(rows)

Structured rows ke liye DictWriter readable mapping-based interface deta hai.

Practice CSV parsing without persistent files

csv-memory.pyPython
import csv
from io import StringIO

text = "name,score\nAman,88\nRiya,92\n"
file_like = StringIO(text)

for row in csv.DictReader(file_like):
    print(row["name"], row["score"])

Run CSV example →

Binary files — brief introduction

Images, PDFs and many non-text formats bytes contain karte hain. Binary mode me bytes read/write hote hain, strings nahi.

binary.pyPython
data = b"\x00\x01\x02"

with open("sample.bin", "wb") as file:
    file.write(data)

with open("sample.bin", "rb") as file:
    print(file.read())

Binary formats ko manually parse karne ki jagah appropriate libraries/formats use karna common practice hai.

Rename and delete with pathlib

manage.pyPython
from pathlib import Path

path = Path("draft.txt")
path.write_text("Draft", encoding="utf-8")

new_path = path.rename("final.txt")
print(new_path)

new_path.unlink()

unlink() file delete karta hai. Delete/rename destructive operations hain, so path ko verify karo and failures handle karo.

Practical safe read/write pattern

marks-file.pyPython
from pathlib import Path

path = Path("marks.txt")

try:
    path.write_text("78\n92\n85\n", encoding="utf-8")
    marks = [
        float(line.strip())
        for line in path.read_text(encoding="utf-8").splitlines()
        if line.strip()
    ]
except OSError as error:
    print("File error:", error)
except ValueError as error:
    print("Invalid mark:", error)
else:
    average = sum(marks) / len(marks) if marks else 0
    print("Average:", average)

Run safe file example →

Playground note: Server execution sandbox ka filesystem temporary ho sakta hai. Same run ke andar read/write practice useful hai, but long-term file persistence assume mat karo.

Common beginner mistakes

  • "w" mode se existing file accidentally overwrite karna.
  • File close karna bhoolna instead of with use karna.
  • Wrong relative path/current working directory ki wajah se file missing samajhna.
  • Encoding omit karke platform-dependent behavior assume karna.
  • writelines() ko newline automatically add karne wala samajhna.
  • Large file ko unnecessarily complete memory me load karna.
  • CSV ko naive split(",") se parse karna.
  • Missing file ke liye broad exception catch karke every bug hide karna.
  • User-provided paths blindly trust karna.
  • Temporary playground files ko permanent storage samajhna.

Beginner best practices

  • Text files ke liye encoding="utf-8" explicitly use karo.
  • File resources ke liye with prefer karo.
  • Modern path handling ke liye pathlib seekho.
  • Read/write mode intentionally choose karo.
  • Large files ko line by line process karo when possible.
  • Specific expected filesystem exceptions handle karo.
  • Structured formats ke liye standard modules use karo, e.g. csv.
  • Destructive operations se pehle target path clearly verify karo.

Chapter checklist

  • open() aur common modes ka purpose clear hai?
  • with statement se file safely manage kar sakte ho?
  • read(), readline() aur line iteration ka difference pata hai?
  • write(), writelines() aur append use kar sakte ho?
  • UTF-8 encoding ka importance samajh aaya?
  • pathlib.Path se common path operations kar sakte ho?
  • FileNotFoundError, PermissionError aur OSError ka basic role clear hai?
  • csv.DictReader/DictWriter ka basic use samajh aaya?

Practice Task — Student Result File Manager

Local Python environment me file-based student result manager banao.

  1. students.csv file create karo.
  2. Columns rakho: name, python, dbms, math.
  3. csv.DictWriter se at least 3 records write karo.
  4. File ko with statement se open karo.
  5. csv.DictReader se records read karo.
  6. Marks ko numeric type me convert karo.
  7. Har student ka average calculate karo.
  8. Highest average student show karo.
  9. Invalid numeric value ko ValueError se handle karo.
  10. Missing file case ko FileNotFoundError se handle karo.
  11. Report ko reports/summary.txt me write karo.
  12. Directory create karne ke liye pathlib use karo.
  13. All text operations me UTF-8 encoding use karo.
  14. Optional: activity log me append mode se one line add karo.