FILE KYA HAI? AUR KYU JARURI HAI? –
Ab tak hum data ko memory/RAM में store कर रहे थे। Program बंद होते ही data गायब।File Handling = Data को Hard Disk में permanent save करना।Real life use:
1.Log Files – Server क्या कर रहा है
2.CSV/Excel – Data Science का 90% data यहीं से आता है
3.Config Files – .json, .ini settings
4.User Data – Login details, notes app
Python में file handle करना बहुत आसान है।
2.OPEN() FUNCTION – FILE KHOLNA –
File से काम करने के लिए पहले उसे open() से खोलना पड़ेगा।
Syntax: file_object = open(“filename”, “mode”)
Important Modes:
| Mode | Kaam | File न हो तो? |
| r | Read only | Error देगा |
| w | Write. पहले का data delete | नई बना देगा |
| a | Append. आखिर में add | नई बना देगा |
| r+ | Read + Write | Error देगा |
| w+ | Read + Write. data delete | नई बना देगा |
| a+ | Read + Append | नई बना देगा |
Extra: t = text mode default, b = binary mode images/video के लिए
Example: open(“photo.jpg”, “rb”)
f = open(“test.txt”, “w”)
f.close() # बंद करना जरूरी है
3.WITH STATEMENT – BEST PRACTICE –
close() भूल गए तो memory leak हो जाएगा।
इसलिए हमेशा with use करो। ये auto close कर देता है।
with open(“test.txt”, “w”) as f:
f.write(“Hello Bhai”)
#yaha f auto close ho gaya
Interview में पूछते हैं: with और normal open-close में फर्क?
Answer: with exception आने पर भी file close कर देता है।
4.WRITING TO FILES—-
4.1 write() – String लिखना
with open(“notes.txt”, “w”) as f:
f.write(“Python File Handling\n”)
f.write(“Chapter 6\n”)
Note: w mode पुराना data मिटा देगा।
4.2 writelines() – List लिखना
lines = [“Line1\n”, “Line2\n”, “Line3\n”]
with open(“notes.txt”, “w”) as f:
f.writelines(lines)
\n खुद डालना पड़ेगा वरना सब एक line में आएगा।
4.3 Append करना
with open(“notes.txt”, “a”) as f:
f.write(“New line added\n”)
4.4 Multiple Data Types
File में सिर्फ string लिख सकते हो। Number हो तो str() करो।
age = 22
with open(“data.txt”, “w”) as f:
f.write(“Age: ” + str(age))
5.READING FROM FILES –
5.1 read() – पूरा file एक बार में
with open(“notes.txt”, “r”) as f:
data = f.read()
print(data)
छोटी file के लिए best है। बड़ी file 1GB की हो तो RAM फुल हो जाएगी।
5.2 readline() – एक-एक line
with open(“notes.txt”, “r”) as f:
print(f.readline()) # 1st line
print(f.readline()) # 2nd line
5.3 readlines() – List of lines
with open(“notes.txt”, “r”) as f:
all_lines = f.readlines()
for line in all_lines:
print(line.strip()) # strip() \n हटाने के लिए
5.4 Loop से पढ़ना – सबसे Best
बड़ी file के लिए यही use करो। Memory कम लगेगी।
with open(“big_data.csv”, “r”) as f:
for line in f:
print(line.strip())
5.5 File Pointer
f.tell() = अभी pointer कहां है
f.seek(0) = pointer को शुरू में ले जाओ
f.read(5) # 5 character पढ़े
f.seek(0) # वापस शुरू
6.CSV FILE HANDLING –
Data Science का सबसे important topic।
import csv
data = [
[“Name”, “Age”, “City”],
[“Aman”, 22, “Lucknow”],
[“Ravi”, 24, “Delhi”]
]
with open(“students.csv”, “w”, newline=””) as f:
writer = csv.writer(f)
writer.writerows(data) # सारी rows
newline=”” Windows में extra blank line रोकता है।
6.2 csv से पढ़ना
import csv
with open(“students.csv”, “r”) as f:
reader = csv.reader(f)
for row in reader:
print(row) # [‘Aman’, ’22’, ‘Lucknow’]
6.3 DictReader और DictWriter
Column name से access करना आसान।
with open(“students.csv”, “r”) as f:
reader = csv.DictReader(f)
for row in reader:
print(row[“Name”], row[“City”])
6.4 Pandas से CSV – DS में यही use होता है
import pandas as pd
df = pd.read_csv(“students.csv”)
df.to_csv(“new_file.csv”, index=False)
1 line में पूरा काम। इसीलिए DS में pandas king है।
7.JSON FILE HANDLING –
API और Web Dev में JSON king है।
JSON = JavaScript Object Notation = Dict जैसा
7.1 JSON लिखना
import json
data = {
“name”: “Aman”,
“skills”: [“Python”, “SQL”],
“active”: True
}
with open(“data.json”, “w”) as f:
json.dump(data, f, indent=4) # indent से readable बनेगा
7.2 JSON पढ़ना
with open(“data.json”, “r”) as f:
data = json.load(f)
print(data[“name”])
7.3 JSON Lines
बड़ी log file में हर line एक JSON होती है।
import json
with open(“logs.jsonl”, “r”) as f:
for line in f:
obj = json.loads(line)
Interview Q: dump vs dumps फर्क?
dump = file में लिखो, dumps = string return करो
8.BINARY FILES – –
Text file नहीं है तो b mode use करो।
with open(“photo.jpg”, “rb”) as f1:
with open(“copy.jpg”, “wb”) as f2:
f2.write(f1.read())
Pickle: Python object को सीधा file में save
import pickle
model = {“weights”: [1,2,3]}
with open(“model.pkl”, “wb”) as f:
pickle.dump(model, f)
Machine Learning model save करने के लिए use होता है।
9.ERROR HANDLING IN FILES –
File न मिली तो program crash न हो।
try:
with open(“imp.txt”, “r”) as f:
data = f.read()
except FileNotFoundError:
print(“File nahi mili bhai”)
except PermissionError:
print(“Permission nahi hai”)
else:
print(“File read ho gayi”)
10. OS और PATH MODULE –
File का नाम, folder check करना।
import os
print(os.getcwd()) # Current folder
print(os.listdir()) # सारी files
os.mkdir(“new_folder”) # Folder बनाओ
os.remove(“old.txt”) # File delete
Path join करना
import os
path = os.path.join(“folder”, “file.txt”) # OS के हिसाब से / या \
11.ADVANCED TOPICS –
11.1 tell() और seek()
बड़ी file में कूद-कूद कर पढ़ना।
f.seek(100) # 100th byte पर जाओ
11.2 Buffering
open(“file.txt”, “w”, buffering=1) line buffer
11.3 File Modes का Summary
x = create only. File पहले से है तो error।
12.REAL WORLD PROJECT IDEAS –
1.Log Analyzer: .log file पढ़ो और error count करो
2.Student Result System: CSV में marks save करो, average निकालो
3.Notes App: .txt में notes save + search करो
4.Data Cleaner: CSV पढ़ो, null हटाओ, नई CSV बनाओ
13.COMMON MISTAKES –
1.close() भूल जाना -> with use करो
2.w mode से पुराना data उड़ा देना
3.Number को direct write() करना -> str() करो
4.CSV में newline=”” न लगाना
5.बड़ी file को read() से पढ़ना -> loop use करो
14.INTERVIEW QUESTIONS –
1.r, w, a, r+, w+ में फर्क?
2.read() vs readlines() vs loop?
3.with क्यों use करते हैं?
4.CSV और JSON में फर्क?
5.बड़ी file कैसे handle करोगे?
SUMMARY
Golden Rules:
1.हमेशा with open() use करो
2.Text = r/w/a, Binary = rb/wb
3.CSV/JSON के लिए built-in module
4.Data Science = pandas.read_csv()
Next: अब हम Pandas chapter करेंगे। वही file handling का upgrade version है।
