File Processing
टेक्स्ट और बाइनरी फाइलों को प्रोसेस करना, डेटा पढ़ना-लिखना, फाइल पॉइंटर्स और पिकलिंग — हर कांसेप्ट को आसानी से समझें!
Introduction →
कम्प्यूटर में प्रयोग के लिए डेटा को मेमोरी में सेव करने के लिए प्रयोग की जाने वाली प्रक्रिया file processing कहलाती है।
पायथन दो प्रकार की फाइल प्रोसेसिंग support करता है:
- Text file: इसमें डेटा सामान्य टेक्स्ट के रूप में सुरक्षित होता है।
- Binary file: इसमें डेटा मशीन फॉर्मेट में सुरक्षित होता है।
1. Open — फाइल को खोलना
2. Read / Write — डेटा पढ़ना या लिखना
3. Close — फाइल को बंद करना
📊 Text File vs Binary File — तुलना
| Feature | Text File | Binary File |
|---|---|---|
| Format | Human readable | Machine readable |
| Extension | .txt | .dat, .bin |
| EOL Character | \n (newline) | No delimiter |
| Open Software | Notepad, VS Code आदि | केवल Python |
| Speed | Slow | Fast |
| Module | Not required | pickle module |
1. Text File →
- यह फाइल ASCII या Unicode char का प्रयोग करके information को simple text के रूप में स्टोर करती है।
- Text file में प्रत्येक लाइन के अंत में एक special character का प्रयोग किया जाता है जिसे EOL "\n" कहते हैं।
- यह फाइल किसी भी सॉफ्टवेयर जैसे – Notepad, Wordpad, Libre Office, MS-Word आदि पर open की जा सकती है।
(i) open()— फ़ाइल को ओपन करने के लिएText file के साथ work start करने से पहले उसे एक विशेष mode में open करने की आवश्यकता होती है।
Open function का प्रयोग फाइल को open करने के लिए किया जाता है और यह दो argument इनपुट करता है।
<file_handle> = open('<file name>', '<mode>')- File handle: यह एक identifier है जिसके द्वारा फाइल को uniquely identify रखा जाता है।
- File name: यह फाइल का नाम है (e.g.
.txt)। - Mode: यह फाइल open करने के उद्देश्य को निर्धारित करता है।
| Mode | Meaning | Description |
|---|---|---|
| w | write | data लिखने के लिए। यदि फाइल है तो ओवरराइट करता है, नहीं है तो नई बनाता है। |
| r | read | data प्राप्त करने के लिए। (Default mode) |
| a | append | data जोड़ने के लिए। |
| w+ | write & read | लिखने और पढ़ने दोनों के लिए। |
| r+ | read & write | पढ़ने और लिखने दोनों के लिए। |
| a+ | append & read | जोड़ने और पढ़ने दोनों के लिए। |
'r' होता है।student = open('marks.txt', 'w')
shop = open('product') # default mode is 'r'(ii) close()— फ़ाइल को बंद करने के लिएकाम पूरा होने के बाद फाइल को close करना आवश्यक है। इससे memory free होती है और data save होता है।
student.close()
shop.close()close() या with statement use करें।(iii) write() & (iv) readline()— डेटा लिखने और पढ़ने के लिएwrite(): यह function स्ट्रिंग को फाइल में लिखता है। EOL '\n' जोड़ना अनिवार्य होता है।
nm = 'Rohit jain' + '\n'
student.write(nm)readline(): फाइल से एक-एक लाइन प्राप्त करने के लिए।
student.readline()15 छात्रों के रिकॉर्ड्स को स्टोर करने के लिए फाइल राइटिंग (File Writing)।
student = open('sdata.txt', 'w')
for a in range(15):
record = ""
rno = int(input("enter roll no. "))
record = record + str(rno) + '\n' # using str() formatting
nm = input("enter name ")
record = record + nm + '\n'
m1 = int(input("enter mark 1 "))
record = record + str(m1) + '\n'
m2 = int(input("enter mark 2 "))
record = record + str(m2) + '\n'
m3 = int(input("enter mark 3 "))
record = record + str(m3) + '\n'
student.write(record)
student.close()ऊपर store किए गए data को पढ़कर display करना।
student = open('sdata.txt', 'r')
for a in range(15):
rno = student.readline()
nm = student.readline()
m1 = student.readline()
m2 = student.readline()
m3 = student.readline()
print("Roll No:", rno, end="")
print("Name:", nm, end="")
print("Marks:", m1, m2, m3)
student.close()More write & read commands:
(A) read()
यह function फाइल से केवल उतनी bytes read करता है जितनी argument में दी गई है। बिना argument के पूरी फाइल read करता है।
f = open('marks.txt', 'r')
data = f.read(30) # पहले 30 bytes read करें
print(data)
all_data = f.read() # बाकी सब read करें
print(all_data)
f.close()(B) readlines()
फाइल से total information read करने के लिए इस function का प्रयोग होता है और यह list return करता है।
f = open('marks.txt', 'r')
lines = f.readlines()
for line in lines:
print(line, end="")
f.close()(C) writelines()
स्ट्रिंग्स की एक list को फाइल में लिखने के लिए।
fruitfile = open('names.txt', 'w')
flist = []
for i in range(5):
nm = input("enter a fruit name: ")
flist.append(nm + '\n')
fruitfile.writelines(flist)
fruitfile.close()Random reading in file
एक फाइल bytes की एक stream होती है। जब फाइल open की जाती है तब file pointer (FP) की position शुरुआत में होती है।
1. tell()— pointer positionFP की current position जानने के लिए।
f = open('fruites.txt', 'r')
print("position:", f.tell())
r = f.read(3)
print("position after 3 bytes:", f.tell())position: 0 position after 3 bytes: 3
2. seek()— change pointerFP की position बदलने के लिए। Syntax: seek(offset, whence)
f.seek(10)
print("position after change:", f.tell())
# whence values:
# 0 = beginning (default)
# 1 = current position
# 2 = end of fileposition after change: 10
2. Binary File Processing →
- बाइनरी फाइल data को उस format में store करती है जिसमें data memory में store किया जाता है।
- बाइनरी फाइल में लाइन के अंत में delimiter नहीं होता है।
- Python के द्वारा बनाई गई binary file केवल python software में open होती है।
- Binary file को
.datextension के साथ save किया जाता है।
(1) pickle module
बाइनरी फाइल में data store तथा access करने के लिए यह मॉड्यूल प्रयोग होता है।
- Serialize (Pickling): data को bytes में बदलना —
pickle.dump() - De-Serialize (Unpickling): bytes को simple format में बदलना —
pickle.load()
import pickle # module import करना अनिवार्य है(2) open() - Binary— फ़ाइल को बाइनरी मोड में ओपन करने के लिए| Mode | Purpose | Description |
|---|---|---|
| wb | write | बाइनरी में लिखना |
| rb | read | बाइनरी से पढ़ना |
| ab | append | बाइनरी में जोड़ना |
| wb+ | write & read | लिखना और पढ़ना |
| rb+ | read & write | पढ़ना और लिखना |
| ab+ | append & read | जोड़ना और पढ़ना |
school = open('student.dat', 'wb')
employ = open('income.dat', 'rb')(3) close()— Closing the fileबाइनरी फाइल को बंद करने के लिए भी close() method का उपयोग होता है।
school.close()(4) dump()— लेखन (Write)pickle.dump() का प्रयोग बाइनरी फाइल में data लिखने के लिए किया जाता है।
import pickle
school = open('student.dat', 'wb')
rno = 101
name = "Rahul"
pickle.dump(rno, school)
pickle.dump(name, school)
school.close()(5) load()— पठन (Read)pickle.load() का प्रयोग बाइनरी फाइल से data प्राप्त करने के लिए किया जाता है।
import pickle
school = open('student.dat', 'rb')
rno = pickle.load(school)
name = pickle.load(school)
print("Roll No:", rno)
print("Name:", name)
school.close()Roll No: 101 Name: Rahul
बाइनरी फाइल में 5 छात्रों का data store करें और फिर उसे read करें।
import pickle
# Writing data
school = open('students.dat', 'wb')
for i in range(5):
rno = int(input("Enter Roll No: "))
name = input("Enter Name: ")
marks = int(input("Enter Marks: "))
record = [rno, name, marks]
pickle.dump(record, school)
school.close()
print("Data saved successfully!")
# Reading data
school = open('students.dat', 'rb')
print("\n--- Student Records ---")
try:
while True:
record = pickle.load(school)
print(f"Roll: {record[0]}, Name: {record[1]}, Marks: {record[2]}")
except EOFError:
school.close()
print("--- End of Records ---")Advanced Operations →
Checking End of File
Python में EOFError exception का प्रयोग करके फाइल के अंत का पता लगाया जाता है।
import pickle
f = open('data.dat', 'rb')
try:
while True:
record = pickle.load(f)
print(record)
except EOFError:
f.close()
print("File reading complete!")Searching in Binary File
बाइनरी फाइल में किसी specific record को search करना।
import pickle
f = open('students.dat', 'rb')
search_rno = int(input("Enter roll no to search: "))
found = False
try:
while True:
record = pickle.load(f)
if record[0] == search_rno:
print("Record Found!")
print(f"Name: {record[1]}, Marks: {record[2]}")
found = True
break
except EOFError:
pass
finally:
f.close()
if not found:
print("Record not found!")Updation of Records
बाइनरी फाइल में किसी record को update करना।
import pickle
f = open('students.dat', 'rb')
records = []
try:
while True:
records.append(pickle.load(f))
except EOFError:
f.close()
update_rno = int(input("Enter roll no to update: "))
for rec in records:
if rec[0] == update_rno:
rec[2] = int(input("Enter new marks: "))
print("Record updated!")
f = open('students.dat', 'wb')
for rec in records:
pickle.dump(rec, f)
f.close()Deletion of Records
Python में रिकॉर्ड हटाने के लिए direct command नहीं है। इसके लिए एक logic का प्रयोग होता है:
- दो फाइल open की जाती हैं (एक read mode में, एक write mode में)।
- पहली फाइल से data प्राप्त किया जाता है और filter करके दूसरी फाइल में store किया जाता है।
- पहली फाइल remove कर दी जाती है।
- दूसरी फाइल का नाम बदलकर पहली फाइल का नाम दे दिया जाता है।
os module का प्रयोग किया जाता है।os.remove()
import os
os.remove('salary.dat')os.rename()
import os
os.rename('temp.dat', 'salary.dat')import pickle, os
f1 = open('students.dat', 'rb')
f2 = open('temp.dat', 'wb')
del_rno = int(input("Enter roll no to delete: "))
try:
while True:
record = pickle.load(f1)
if record[0] != del_rno:
pickle.dump(record, f2)
else:
print("Record deleted!")
except EOFError:
f1.close()
f2.close()
os.remove('students.dat')
os.rename('temp.dat', 'students.dat')
print("Done!")Complete Programs →
एक text file में कुल words count करने का program।
f = open('story.txt', 'r')
data = f.read()
words = data.split()
print("Total words:", len(words))
f.close()f = open('story.txt', 'r')
count = 0
for line in f:
if line[0] == 'T' or line[0] == 't':
count += 1
print("Lines starting with T/t:", count)
f.close()f1 = open('source.txt', 'r')
f2 = open('destination.txt', 'w')
for line in f1:
f2.write(line)
f1.close()
f2.close()
print("File copied successfully!")Employee salary data को binary file में store और display करना।
import pickle
# Writing employee data
emp = open('employee.dat', 'wb')
n = int(input("How many employees? "))
for i in range(n):
eid = int(input("Enter Employee ID: "))
name = input("Enter Name: ")
salary = float(input("Enter Salary: "))
record = {'id': eid, 'name': name, 'salary': salary}
pickle.dump(record, emp)
emp.close()
# Reading & displaying
emp = open('employee.dat', 'rb')
print("\n===== Employee Report =====")
total = 0
try:
while True:
rec = pickle.load(emp)
print(f"ID: {rec['id']} | Name: {rec['name']} | Salary: ₹{rec['salary']}")
total += rec['salary']
except EOFError:
emp.close()
print(f"\nTotal Salary: ₹{total}")with Statement →
with statement का प्रयोग करने से फाइल automatically close हो जाती है। इसमें close() लिखने की आवश्यकता नहीं होती।
with statement Python का best practice है file handling के लिए। यह errors और memory leaks से बचाता है।with open('<filename>', '<mode>') as <file_handle>:
# file operations here
# file automatically closes after this blockwith open('notes.txt', 'w') as f:
f.write("Hello World\n")
f.write("Python is great!\n")
# file auto-closed herewith open('notes.txt', 'r') as f:
for line in f:
print(line, end="")
# file auto-closed hereimport pickle
# Write
with open('data.dat', 'wb') as f:
pickle.dump([1, 2, 3], f)
pickle.dump("Hello", f)
# Read
with open('data.dat', 'rb') as f:
try:
while True:
data = pickle.load(f)
print(data)
except EOFError:
print("Done reading!")[1, 2, 3] Hello Done reading!
Practice Questions →
इन programs को खुद लिखने का प्रयास करें — Chapter 8 को और अच्छे से समझने के लिए 💪
Chapter 8 — Key Points :
- Text file human readable format में data store करती है
- Binary file machine format में data store करती है — pickle module required
- dump() — data लिखना, load() — data पढ़ना
- tell() — pointer position, seek() — pointer change
- with statement — file auto-close, best practice!
- Delete records: read → filter → write to temp → rename