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.
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.
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
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 toFileNotFoundError."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 toFileExistsError."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.
"w" mode existing content erase kar sakta hai. Production data par mode choose karte waqt deliberate raho.Use with for automatic cleanup
with open("notes.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
# file automatically closed after the blockContext 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
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()
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
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
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
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
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()
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.
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
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()
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.
Check paths only when it helps the flow
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
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
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.
from pathlib import Path
path = Path("notes.txt")
print(path.resolve())../../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.
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
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
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"])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.
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
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
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)Common beginner mistakes
"w"mode se existing file accidentally overwrite karna.- File close karna bhoolna instead of
withuse 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
withprefer karo. - Modern path handling ke liye
pathlibseekho. - 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?withstatement 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.Pathse common path operations kar sakte ho?FileNotFoundError,PermissionErroraurOSErrorka basic role clear hai?csv.DictReader/DictWriterka basic use samajh aaya?
Practice Task — Student Result File Manager
Local Python environment me file-based student result manager banao.
students.csvfile create karo.- Columns rakho:
name,python,dbms,math. csv.DictWriterse at least 3 records write karo.- File ko
withstatement se open karo. csv.DictReaderse records read karo.- Marks ko numeric type me convert karo.
- Har student ka average calculate karo.
- Highest average student show karo.
- Invalid numeric value ko
ValueErrorse handle karo. - Missing file case ko
FileNotFoundErrorse handle karo. - Report ko
reports/summary.txtme write karo. - Directory create karne ke liye
pathlibuse karo. - All text operations me UTF-8 encoding use karo.
- Optional: activity log me append mode se one line add karo.