File Processing

Chapter 8 • Python
Chapter 8 • Python

File Processing

टेक्स्ट और बाइनरी फाइलों को प्रोसेस करना, डेटा पढ़ना-लिखना, फाइल पॉइंटर्स और पिकलिंग — हर कांसेप्ट को आसानी से समझें!

Text Files
Binary Files
Seek & Tell
Pickle Module

Introduction →

कम्प्यूटर में प्रयोग के लिए डेटा को मेमोरी में सेव करने के लिए प्रयोग की जाने वाली प्रक्रिया file processing कहलाती है।

पायथन दो प्रकार की फाइल प्रोसेसिंग support करता है:

  • Text file: इसमें डेटा सामान्य टेक्स्ट के रूप में सुरक्षित होता है।
  • Binary file: इसमें डेटा मशीन फॉर्मेट में सुरक्षित होता है।
📝 File processing के 3 मुख्य स्टेप्स हैं:
1. Open — फाइल को खोलना
2. Read / Write — डेटा पढ़ना या लिखना
3. Close — फाइल को बंद करना

📊 Text File vs Binary File — तुलना

FeatureText FileBinary File
FormatHuman readableMachine readable
Extension.txt.dat, .bin
EOL Character\n (newline)No delimiter
Open SoftwareNotepad, VS Code आदिकेवल Python
SpeedSlowFast
ModuleNot requiredpickle 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 इनपुट करता है।

python
<file_handle> = open('<file name>', '<mode>')
  • File handle: यह एक identifier है जिसके द्वारा फाइल को uniquely identify रखा जाता है।
  • File name: यह फाइल का नाम है (e.g. .txt)।
  • Mode: यह फाइल open करने के उद्देश्य को निर्धारित करता है।
Mode के प्रकार:
ModeMeaningDescription
wwritedata लिखने के लिए। यदि फाइल है तो ओवरराइट करता है, नहीं है तो नई बनाता है।
rreaddata प्राप्त करने के लिए। (Default mode)
aappenddata जोड़ने के लिए।
w+write & readलिखने और पढ़ने दोनों के लिए।
r+read & writeपढ़ने और लिखने दोनों के लिए।
a+append & readजोड़ने और पढ़ने दोनों के लिए।
📝 यदि mode नहीं दिया गया है तब default mode 'r' होता है।
python
student = open('marks.txt', 'w')
shop = open('product') # default mode is 'r'
(ii) close()फ़ाइल को बंद करने के लिए

काम पूरा होने के बाद फाइल को close करना आवश्यक है। इससे memory free होती है और data save होता है।

python
student.close()
shop.close()
⚠️ फाइल close करना भूलने से data loss हो सकता है! हमेशा close() या with statement use करें।
(iii) write() & (iv) readline()डेटा लिखने और पढ़ने के लिए

write(): यह function स्ट्रिंग को फाइल में लिखता है। EOL '\n' जोड़ना अनिवार्य होता है।

python
nm = 'Rohit jain' + '\n'
student.write(nm)

readline(): फाइल से एक-एक लाइन प्राप्त करने के लिए।

python
student.readline()
Program 1 — Student Data (Write)

15 छात्रों के रिकॉर्ड्स को स्टोर करने के लिए फाइल राइटिंग (File Writing)।

python
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()
Program 2 — Student Data (Read)

ऊपर store किए गए data को पढ़कर display करना।

python
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 करता है।

python
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 करता है।

python
f = open('marks.txt', 'r')
lines = f.readlines()
for line in lines:
    print(line, end="")
f.close()

(C) writelines()

स्ट्रिंग्स की एक list को फाइल में लिखने के लिए।

python
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 position

FP की current position जानने के लिए।

python
f = open('fruites.txt', 'r')
print("position:", f.tell())
r = f.read(3)
print("position after 3 bytes:", f.tell())
Output
position: 0
position after 3 bytes: 3
2. seek()change pointer

FP की position बदलने के लिए। Syntax: seek(offset, whence)

python
f.seek(10)
print("position after change:", f.tell())

# whence values:
# 0 = beginning (default)
# 1 = current position
# 2 = end of file
Output
position after change: 10

2. Binary File Processing →

  • बाइनरी फाइल data को उस format में store करती है जिसमें data memory में store किया जाता है।
  • बाइनरी फाइल में लाइन के अंत में delimiter नहीं होता है।
  • Python के द्वारा बनाई गई binary file केवल python software में open होती है।
  • Binary file को .dat extension के साथ save किया जाता है।

(1) pickle module

बाइनरी फाइल में data store तथा access करने के लिए यह मॉड्यूल प्रयोग होता है।

  • Serialize (Pickling): data को bytes में बदलना — pickle.dump()
  • De-Serialize (Unpickling): bytes को simple format में बदलना — pickle.load()
python
import pickle  # module import करना अनिवार्य है
(2) open() - Binaryफ़ाइल को बाइनरी मोड में ओपन करने के लिए
ModePurposeDescription
wbwriteबाइनरी में लिखना
rbreadबाइनरी से पढ़ना
abappendबाइनरी में जोड़ना
wb+write & readलिखना और पढ़ना
rb+read & writeपढ़ना और लिखना
ab+append & readजोड़ना और पढ़ना
python
school = open('student.dat', 'wb')
employ = open('income.dat', 'rb')
(3) close()Closing the file

बाइनरी फाइल को बंद करने के लिए भी close() method का उपयोग होता है।

python
school.close()
(4) dump()लेखन (Write)

pickle.dump() का प्रयोग बाइनरी फाइल में data लिखने के लिए किया जाता है।

python
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 प्राप्त करने के लिए किया जाता है।

python
import pickle

school = open('student.dat', 'rb')
rno = pickle.load(school)
name = pickle.load(school)
print("Roll No:", rno)
print("Name:", name)
school.close()
Output
Roll No: 101
Name: Rahul
Program — Binary File (Write & Read Students)

बाइनरी फाइल में 5 छात्रों का data store करें और फिर उसे read करें।

python
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 का प्रयोग करके फाइल के अंत का पता लगाया जाता है।

python
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 करना।

python
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 करना।

python
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 कर दी जाती है।
  • दूसरी फाइल का नाम बदलकर पहली फाइल का नाम दे दिया जाता है।
💡 इस process के लिए os module का प्रयोग किया जाता है।

os.remove()

python
import os
os.remove('salary.dat')

os.rename()

python
import os
os.rename('temp.dat', 'salary.dat')
Complete Deletion Program
python
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 →

Program — Count words in a text file

एक text file में कुल words count करने का program।

python
f = open('story.txt', 'r')
data = f.read()
words = data.split()
print("Total words:", len(words))
f.close()
Program — Count lines starting with a specific letter
python
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()
Program — Copy contents from one file to another
python
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!")
Program — Employee Salary (Binary File)

Employee salary data को binary file में store और display करना।

python
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 से बचाता है।
Syntax
python
with open('<filename>', '<mode>') as <file_handle>:
    # file operations here
    # file automatically closes after this block
Writing with 'with'
python
with open('notes.txt', 'w') as f:
    f.write("Hello World\n")
    f.write("Python is great!\n")
# file auto-closed here
Reading with 'with'
python
with open('notes.txt', 'r') as f:
    for line in f:
        print(line, end="")
# file auto-closed here
Binary File with 'with' Statement
python
import 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!")
Output
[1, 2, 3]
Hello
Done reading!

Practice Questions →

इन programs को खुद लिखने का प्रयास करें — Chapter 8 को और अच्छे से समझने के लिए 💪

Q1
Write a program to create a text file and store 5 student names in it.
Q2
Write a program to read a text file line by line and display the content.
Q3
Write a program to count the number of vowels in a text file.
Q4
Write a program to count the number of lines, words, and characters in a text file.
Q5
Write a program to copy all lines starting with 'P' from one file to another.
Q6
Write a program to create a binary file to store employee data (eid, name, salary) using pickle.
Q7
Write a program to read and display all records from a binary file.
Q8
Write a program to search for a specific employee by ID in a binary file.
Q9
Write a program to update the salary of an employee in a binary file.
Q10
Write a program to delete a record from a binary file using os module.
Q11
Write a program using 'with' statement to write and read a text file.
Q12
Write a program to merge two text files into a third file.
Q13
Write a program to count occurrences of word 'the' in a text file.
Q14
Write a program to store a list of dictionaries in a binary file and display them.
Q15
Write a program to find the longest line in a text file.

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
Hi! 👋
KnoblyAI
Online

Hello! 👋

Your futuristic AI learning companion

KnoblyAI can make mistakes. Double-check important replies.