File Processing in Python – Chapter 7 | O Level M3-R5 | Boosting Skills

File Processing in Python – NIELIT O Level (M3-R5)

इस chapter में हम Python में File Handling सीखेंगे — इसमें शामिल हैं File Opening Modes, Reading & Writing Data, File Functions जैसे open(), close(), read(), readline(), write(), seek(), tell() और Command Line Arguments का प्रयोग।

👉 Swipe to see more
1️⃣ Concept of Files

📘 Introduction

File Handling का मतलब होता है data को computer memory (storage) में permanently store करना। जब कोई program execute होता है, तो data temporary रूप से RAM में store होता है। लेकिन अगर हमें data को save करना है ताकि program बंद होने के बाद भी वो रहे — तो हम files का उपयोग करते हैं।

Python file handling को बहुत आसान बनाता है — आप text files, binary files, और CSV files तक को आसानी से manage कर सकते हैं।


📁 1️⃣ Types of Files in Python

  • Text Files (.txt) → Contain human-readable text (letters, digits, etc.)
  • Binary Files (.bin, .jpg, .exe) → Contain non-text data like images, videos, etc.
  • CSV Files (.csv) → Contain tabular data (rows & columns), often used for Excel-like data.

🧱 2️⃣ Opening a File

किसी file को access करने के लिए Python का built-in function open() उपयोग किया जाता है। इसका syntax है:


file_object = open("filename", "mode")
  

Example:


f = open("demo.txt", "w")   # open file in write mode
f.write("Hello Python!")
f.close()
  

Output:
A new file demo.txt is created containing the text: “Hello Python!”


🔍 3️⃣ Understanding File Modes (Deep Explanation + Examples)

File mode यह बताता है कि file के साथ क्या operation होगा — read, write, append, binary, or text.

ModeDescriptionExample
"r" Read Mode – file पढ़ने के लिए; अगर file नहीं है तो error।
f = open("data.txt", "r")
print(f.read())
f.close()
"w" Write Mode – नई file बनाता है; existing content delete करता है।
f = open("data.txt", "w")
f.write("Hello World")
f.close()
"a" Append Mode – Existing file के end में data जोड़ता है।
f = open("data.txt", "a")
f.write("\\nNew line added")
f.close()
"r+" Read + Write Mode – File को पढ़ और modify दोनों कर सकता है।
f = open("data.txt", "r+")
print(f.read())
f.write("\\nExtra data")
f.close()
"w+" Write + Read Mode – File को overwrite करता है और पढ़ भी सकता है।
f = open("data.txt", "w+")
f.write("Python Rocks!")
f.seek(0)
print(f.read())
f.close()
"a+" Append + Read Mode – End में data जोड़ता है और read भी कर सकता है।
f = open("data.txt", "a+")
f.write("\\nAdded later")
f.seek(0)
print(f.read())
f.close()
"rb" Read Binary – Binary file (images/videos) को पढ़ने के लिए।
f = open("photo.jpg", "rb")
data = f.read()
print(len(data))
f.close()
"wb" Write Binary – Binary mode में नया file बनाता है।
f = open("image_copy.jpg", "wb")
f.write(b"BinaryData")
f.close()

📜 4️⃣ Working with Text Files

Text files human-readable होती हैं। आप write() और read() methods का उपयोग करके content लिख और पढ़ सकते हैं।


# Writing into a text file
with open("textfile.txt", "w") as f:
    f.write("Python File Handling Example\n")
    f.write("Second Line")

# Reading the file
with open("textfile.txt", "r") as f:
    data = f.read()
    print(data)
  

Output:
Python File Handling Example
Second Line


📂 5️⃣ Working with Binary Files

Binary files में data text के बजाय binary (0s और 1s) format में store होता है। ये files images, audio, video जैसी होती हैं।

💻 Example: Copy Image using Binary File


# Copying binary file
with open("input.jpg", "rb") as src:
    data = src.read()

with open("output_copy.jpg", "wb") as dest:
    dest.write(data)

print("Image copied successfully!")
  

Output:
Image copied successfully!


🧮 6️⃣ Working with CSV Files

Python में CSV files के लिए built-in csv module होता है। यह table-like data को rows और columns के format में manage करता है।

📦 Step 1: Importing CSV Module


import csv
  

💻 Example 1: Writing Data into CSV File


import csv

# Writing data into CSV
with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "Grade"])
    writer.writerow(["Ravi", 20, "A"])
    writer.writerow(["Priya", 21, "B"])
    writer.writerow(["Amit", 19, "A"])

print("CSV file created successfully!")
  

Output:
CSV file students.csv created with following data:
Name, Age, Grade
Ravi, 20, A
Priya, 21, B
Amit, 19, A

💻 Example 2: Reading Data from CSV File


import csv

# Reading data from CSV
with open("students.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
  

Output:
['Name', 'Age', 'Grade']
['Ravi', '20', 'A']
['Priya', '21', 'B']
['Amit', '19', 'A']


⚙️ 7️⃣ Best Practice — Using “with open()”

with keyword automatically file को close कर देता है — इसलिए यह सबसे सुरक्षित और clean तरीका है।


with open("example.txt", "r") as f:
    content = f.read()
    print(content)
  

✅ No need to use f.close(); it closes automatically.


💬 Interview FAQs

  • Q: What are different types of files in Python?
    A: Text files, Binary files, and CSV files.
  • Q: What module is used for CSV file handling?
    A: Python’s built-in csv module.
  • Q: Difference between write() and writelines()?
    A: write() writes one string, while writelines() writes multiple lines from list/tuple.
  • Q: What is the difference between “r+” and “w+”?
    A: r+ does not erase file content; w+ overwrites it completely.
  • Q: How to ensure a file is always closed?
    A: Use with open() block — it closes automatically.
  • Q: Can we handle Excel data using CSV files?
    A: Yes, CSV files are used to store and share tabular data similar to Excel.
2️⃣ Opening and Closing a File

📘 Introduction

किसी भी file के साथ काम करने का पहला step उसे open() करना और आखिरी step उसे close() करना होता है। Python में यह process बहुत आसान है। Text files, Binary files और CSV files – तीनों को खोलने और बंद करने का तरीका लगभग समान होता है, सिर्फ mode और modules अलग होते हैं।


📂 1️⃣ Opening a File

File को open करने के लिए Python का built-in open() function उपयोग किया जाता है। Syntax:


file_object = open("filename", "mode")
  

👉 यहाँ "mode" बताता है कि file पढ़नी है, लिखनी है या append करनी है।


📋 2️⃣ File Opening Modes with Example

ModeDescriptionExample
"r" Read mode — file पढ़ने के लिए; अगर file नहीं है तो error देता है।
f = open("demo.txt", "r")
print(f.read())
f.close()
"w" Write mode — file को overwrite करता है या नया बनाता है।
f = open("demo.txt", "w")
f.write("New content")
f.close()
"a" Append mode — existing file के अंत में data जोड़ता है।
f = open("demo.txt", "a")
f.write("\\nAdded text")
f.close()
"r+" Read + Write (file के बीच में भी लिख सकते हैं)।
f = open("demo.txt", "r+")
print(f.read())
f.write("\\nExtra data")
f.close()
"b" Binary mode — non-text files जैसे images/videos को handle करता है।
f = open("photo.jpg", "rb")
data = f.read()
f.close()

💻 Example 1: Opening and Writing to Text File


# Open file in write mode
f = open("example.txt", "w")
f.write("Hello, this is a sample text file.")
f.close()

print("Data written successfully!")
  

Output:
Data written successfully.
(File example.txt created successfully.)


📘 3️⃣ Closing a File

जब आप किसी file पर operation पूरा कर लेते हैं, तो उसे close() method से बंद करना ज़रूरी होता है। इससे data properly save होता है और memory release होती है।


f = open("demo.txt", "w")
f.write("File handling in Python.")
f.close()
print("File closed successfully.")
  

Output:
File closed successfully.


⚙️ 4️⃣ Using with open() Statement

File को manually close() करने की जगह आप with statement का उपयोग कर सकते हैं। इससे file automatically close हो जाती है, even अगर कोई error भी आ जाए।

💻 Example 2: Using with block


with open("data.txt", "w") as f:
    f.write("Using with block is safer!")

print("File closed automatically after the block.")
  

Output:
File closed automatically after the block.

  • ✅ File automatically close हो जाती है।
  • ✅ Data loss नहीं होता।
  • ✅ Clean और readable code रहता है।

🧮 5️⃣ Opening and Closing a Binary File

Binary files जैसे image, video या audio को handle करने के लिए mode में "b" जोड़ते हैं।

💻 Example 3: Copying Image File


# Copy binary file
with open("photo.jpg", "rb") as source:
    data = source.read()

with open("copy_photo.jpg", "wb") as target:
    target.write(data)

print("Binary file copied successfully.")
  

Output:
Binary file copied successfully.


📊 6️⃣ Opening and Closing a CSV File

CSV files को handle करने के लिए csv module को import करना पड़ता है। यह files table-like data store करती हैं — जैसे Excel।

💻 Example 4: Writing CSV File


import csv

# Writing data into CSV file
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "Marks"])
    writer.writerow(["Ravi", 20, 85])
    writer.writerow(["Anita", 22, 90])

print("CSV file created successfully!")
  

Output:
CSV file data.csv created successfully with records of students.

💻 Example 5: Reading CSV File


import csv

# Reading CSV file
with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
  

Output:
['Name', 'Age', 'Marks']
['Ravi', '20', '85']
['Anita', '22', '90']


🧠 7️⃣ Checking File Status (Open or Closed)

Python में किसी file के open या closed होने की स्थिति check करने के लिए file_object.closed attribute का उपयोग किया जाता है।


f = open("sample.txt", "w")
print("Before closing:", f.closed)
f.close()
print("After closing:", f.closed)
  

Output:
Before closing: False
After closing: True


💬 Interview FAQs

  • Q: What is the use of open() function?
    A: It opens the file and returns a file object for performing operations.
  • Q: What is the difference between open() and with open()?
    A: with open() automatically closes the file after use, while open() requires manual close().
  • Q: Which module is required for handling CSV files?
    A: The csv module (import csv).
  • Q: What happens if file is opened in read mode but doesn't exist?
    A: Python throws FileNotFoundError.
  • Q: Can binary files be opened without 'b' mode?
    A: No, doing so will cause data corruption.
3️⃣ Reading from a File

📘 Introduction

Python में किसी file का content पढ़ने के लिए file को read mode ("r") या binary mode ("rb") में open किया जाता है। आप file के data को एक साथ या line-by-line पढ़ सकते हैं। CSV files के लिए Python csv module provide करता है।


📂 1️⃣ Reading from a Text File

Text files human-readable होती हैं। इन्हें open करके हम read(), readline(), या readlines() से data प्राप्त करते हैं।

💻 Example 1: Reading Entire File


# Create a file for reading
with open("demo.txt", "w") as f:
    f.write("Python is powerful.\n")
    f.write("File handling is easy.\n")
    f.write("Keep practicing daily.")

# Read complete content
with open("demo.txt", "r") as f:
    data = f.read()
    print("File content:\n", data)
  

Output:
Python is powerful.
File handling is easy.
Keep practicing daily.


📖 2️⃣ read() Function

read() पूरी file को एक single string के रूप में return करता है। Optionally आप characters की संख्या specify कर सकते हैं।

💻 Example 2: Read Limited Characters


with open("demo.txt", "r") as f:
    data = f.read(12)
    print("First 12 characters:", data)
  

Output:
First 12 characters: Python is po


🧾 3️⃣ readline() Function

readline() एक बार में एक line पढ़ता है। हर बार call करने पर अगली line मिलती है।

💻 Example 3: Read Line by Line


with open("demo.txt", "r") as f:
    line1 = f.readline()
    line2 = f.readline()
    print("Line 1:", line1.strip())
    print("Line 2:", line2.strip())
  

Output:
Line 1: Python is powerful.
Line 2: File handling is easy.


🧮 4️⃣ readlines() Function

readlines() सभी lines को एक list में return करता है। हर element एक line represent करता है।

💻 Example 4: Using readlines()


with open("demo.txt", "r") as f:
    lines = f.readlines()
    print(lines)
  

Output:
['Python is powerful.\\n', 'File handling is easy.\\n', 'Keep practicing daily.']


⚙️ 5️⃣ Efficient Line-by-Line Reading

बड़ी files (जैसे logs या CSV) को efficiently पढ़ने के लिए for loop का उपयोग करना सबसे अच्छा तरीका है।

💻 Example 5: Reading Large File Efficiently


with open("demo.txt", "r") as f:
    for line in f:
        print(line.strip())
  

Output:
Python is powerful.
File handling is easy.
Keep practicing daily.


📊 6️⃣ Reading CSV Files (Using csv Module)

CSV (Comma-Separated Values) file tabular data store करती है। Python में इसे पढ़ने के लिए csv.reader का उपयोग किया जाता है।

💻 Example 6: Reading CSV Data


import csv

# Create sample CSV
with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "Marks"])
    writer.writerow(["Ravi", 20, 85])
    writer.writerow(["Anita", 22, 90])

# Read CSV File
with open("students.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
  

Output:
['Name', 'Age', 'Marks']
['Ravi', '20', '85']
['Anita', '22', '90']

💡 Tip: Each row is read as a list of strings.


🧠 7️⃣ Reading CSV using DictReader

DictReader class CSV data को dictionary format में पढ़ता है जहाँ column headers key के रूप में use होते हैं।

💻 Example 7: Using DictReader


import csv

with open("students.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(dict(row))
  

Output:
{'Name': 'Ravi', 'Age': '20', 'Marks': '85'}
{'Name': 'Anita', 'Age': '22', 'Marks': '90'}


💾 8️⃣ Reading from a Binary File

Binary files जैसे image/video को पढ़ने के लिए mode में "rb" का उपयोग किया जाता है।

💻 Example 8: Reading Binary File


# Reading binary data
with open("photo.jpg", "rb") as f:
    data = f.read()
    print("Total bytes read:", len(data))
  

Output:
Total bytes read: 24567

💡 Tip: Binary data को normally print नहीं किया जा सकता, लेकिन आप इसकी length या copy कर सकते हैं।


🧮 9️⃣ Example Program – Count Words and Lines in File


# Counting words and lines
lines = words = 0
with open("demo.txt", "r") as f:
    for line in f:
        lines += 1
        words += len(line.split())

print("Total Lines:", lines)
print("Total Words:", words)
  

Output:
Total Lines: 3
Total Words: 9


💬 Interview FAQs

  • Q: Which mode is used to read text files?
    A: "r" mode.
  • Q: How can we read binary files?
    A: Use "rb" mode for reading binary data.
  • Q: What is the difference between read(), readline(), and readlines()?
    A:
    • read() → Reads entire file as a single string.
    • readline() → Reads one line at a time.
    • readlines() → Returns list of all lines.
  • Q: Which module is used for reading CSV files?
    A: Python’s built-in csv module.
  • Q: What is DictReader in csv module?
    A: It reads each row as a dictionary where column headers are keys.
4️⃣ Writing onto a File

📘 Introduction

File में data को store करने के लिए Python write() और writelines() functions provide करता है। आप text, binary और CSV files तीनों में data write कर सकते हैं। File को write करने से पहले उसे proper mode में open करना जरूरी है जैसे "w", "a", "wb" आदि।


📂 1️⃣ Writing into Text Files

Text files में human-readable text लिखा जाता है। "w" mode नया file बनाता है या पुराने data को overwrite करता है। "a" mode existing file में नया data जोड़ता है।

💻 Example 1: Writing Text Data


# Writing into a file
with open("info.txt", "w") as f:
    f.write("Welcome to Python File Handling!\n")
    f.write("This is the second line.\n")

print("Data written successfully.")
  

Output:
Data written successfully.
(File info.txt created with two lines.)


✍️ 2️⃣ Appending Data to an Existing File

अगर आप पुराने content को delete किए बिना नया data जोड़ना चाहते हैं, तो file को "a" या "a+" mode में खोलिए।

💻 Example 2: Appending Text


# Append mode
with open("info.txt", "a") as f:
    f.write("This line is added later.\n")

print("New line appended successfully.")
  

Output:
New line appended successfully.


📋 3️⃣ Writing Multiple Lines using writelines()

writelines() function एक list या tuple of strings accept करता है और सभी lines को एक साथ write करता है।

💻 Example 3: Writing List of Strings


lines = [
    "Python makes file handling easy.\n",
    "It supports text, binary, and CSV files.\n",
    "Practice makes you perfect!\n"
]

with open("notes.txt", "w") as f:
    f.writelines(lines)

print("Multiple lines written successfully.")
  

Output:
Multiple lines written successfully.


🧮 4️⃣ Writing Binary Files (Images / Audio / Videos)

Binary files में data bytes format में store होता है। इन्हें handle करने के लिए file को "wb" या "rb" mode में खोलना होता है। इस example में हम एक image file को copy करेंगे।

💻 Example 4: Copying Binary File


# Copying image file
with open("photo.jpg", "rb") as src:
    data = src.read()

with open("photo_copy.jpg", "wb") as dest:
    dest.write(data)

print("Binary file written (image copied) successfully.")
  

Output:
Binary file written (image copied) successfully.

💡 Note: Binary data को print नहीं किया जा सकता, लेकिन length या copy की जा सकती है।


📊 5️⃣ Writing into CSV Files (Using csv Module)

CSV files में data rows और columns के रूप में store होता है। Python में इन्हें handle करने के लिए built-in csv module का उपयोग किया जाता है।

📦 Step 1: Importing CSV Module


import csv
  

💻 Example 5: Writing Data into CSV File


import csv

# Writing student records into CSV
with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "Marks"])
    writer.writerow(["Ravi", 20, 85])
    writer.writerow(["Anita", 22, 90])
    writer.writerow(["Kiran", 21, 95])

print("CSV file written successfully!")
  

Output:
CSV file students.csv created successfully with student details.


🧠 6️⃣ Writing Dictionary Data using DictWriter

DictWriter class dictionary objects को CSV rows के रूप में लिखता है। यह fieldnames का उपयोग करता है columns को identify करने के लिए।

💻 Example 6: Writing with DictWriter


import csv

data = [
    {"Name": "Ravi", "Age": 20, "Marks": 85},
    {"Name": "Anita", "Age": 22, "Marks": 90},
    {"Name": "Kiran", "Age": 21, "Marks": 95}
]

with open("students_dict.csv", "w", newline="") as file:
    fieldnames = ["Name", "Age", "Marks"]
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(data)

print("CSV file (dictionary) written successfully.")
  

Output:
CSV file (dictionary) written successfully.


🧮 7️⃣ Example Program: Writing User Input into File

इस example में user से नाम और उम्र लेकर file में store किया गया है।


name = input("Enter your name: ")
age = input("Enter your age: ")

with open("userdata.txt", "w") as f:
    f.write("Name: " + name + "\\n")
    f.write("Age: " + age + "\\n")

print("User data saved successfully.")
  

Output:
Enter your name: Rahul
Enter your age: 19
User data saved successfully.


⚙️ 8️⃣ Example Program: Writing Numbers from 1–10


with open("numbers.txt", "w") as f:
    for i in range(1, 11):
        f.write(str(i) + "\\n")

print("Numbers written to file successfully.")
  

Output:
Numbers written to file successfully.
(File contains 1 to 10 on new lines.)


📚 9️⃣ Difference Between Write and Append Mode

FeatureWrite Mode ("w")Append Mode ("a")
File CreationCreates new or overwrites existing fileCreates file if not present
Existing DataDeletedPreserved
Use CaseStart new contentAdd more data at end

💬 Interview FAQs

  • Q: Which functions are used to write data into a file?
    A: write(), writelines(), and for CSV — csv.writer().
  • Q: What happens if we open an existing file in "w" mode?
    A: It overwrites (deletes) the old content.
  • Q: How to append data without deleting old content?
    A: Use "a" mode.
  • Q: Which module is used for writing CSV data?
    A: csv module (with writer or DictWriter).
  • Q: How to write binary data to a file?
    A: Open file in "wb" mode and write bytes data.
5️⃣ Important File Functions

📘 Introduction

Python में files के साथ काम करते समय कुछ built-in file object methods और os module functions बहुत महत्वपूर्ण होते हैं। ये methods हमें file के अंदर data read/write करने, position control करने, और file की properties जानने में मदद करते हैं।


📂 1️⃣ Common File Object Attributes

जब आप open() से कोई file खोलते हैं, तो Python एक file object return करता है जिसमें कुछ built-in properties होती हैं।

💻 Example 1: Checking File Attributes


# Opening file in write mode
f = open("demo.txt", "w")
print("File Name:", f.name)
print("Mode:", f.mode)
print("Is File Closed?:", f.closed)
f.close()
print("After closing:", f.closed)
  

Output:
File Name: demo.txt
Mode: w
Is File Closed?: False
After closing: True

💡 Explanation: - f.name → file का नाम बताता है। - f.mode → file किस mode में खुली है। - f.closed → True/False बताता है कि file बंद है या नहीं।


🧭 2️⃣ tell() and seek() Functions

File pointer की current position को जानने और बदलने के लिए tell() और seek() का उपयोग किया जाता है।

💻 Example 2: Using tell() and seek()


# Writing and reading file pointer position
with open("demo.txt", "w") as f:
    f.write("Hello Python World!")

with open("demo.txt", "r") as f:
    print("Current position:", f.tell())
    content = f.read(5)
    print("Read content:", content)
    print("After reading 5 chars, position:", f.tell())
    f.seek(0)
    print("After seek(0), position:", f.tell())
  

Output:
Current position: 0
Read content: Hello
After reading 5 chars, position: 5
After seek(0), position: 0

💡 Explanation: - tell() file pointer की current position बताता है। - seek(0) pointer को file की शुरुआत पर ले जाता है।


📖 3️⃣ readline() and readlines() Functions

ये functions file को line-by-line पढ़ने के लिए उपयोग होते हैं।

💻 Example 3: Using readline()


with open("demo.txt", "r") as f:
    line1 = f.readline()
    print("Line 1:", line1)
  

Output:
Line 1: Hello Python World!

💻 Example 4: Using readlines()


with open("demo.txt", "r") as f:
    all_lines = f.readlines()
    print("All lines as list:", all_lines)
  

Output:
All lines as list: ['Hello Python World!']


🧮 4️⃣ write() and writelines() Functions

write() एक बार में एक string लिखता है, जबकि writelines() कई lines एक साथ लिख सकता है।

💻 Example 5: Using write() and writelines()


lines = ["Line 1\\n", "Line 2\\n", "Line 3\\n"]
with open("sample.txt", "w") as f:
    f.write("This is a single line.\\n")
    f.writelines(lines)

print("Data written successfully.")
  

Output:
Data written successfully.


📦 5️⃣ os Module Functions for File Handling

Python का os module operating system level पर files और folders को manage करने के लिए इस्तेमाल होता है। नीचे कुछ commonly used functions दिए गए हैं:

💻 Example 6: os Functions


import os

# Check if file exists
if os.path.exists("sample.txt"):
    print("File exists!")

# Rename file
os.rename("sample.txt", "renamed.txt")

# Delete file
os.remove("renamed.txt")
print("File renamed and deleted successfully!")
  

Output:
File exists!
File renamed and deleted successfully!

💡 Explanation:
- os.path.exists() → file मौजूद है या नहीं बताता है। - os.rename(old, new) → file का नाम बदलता है। - os.remove() → file delete करता है।


📊 6️⃣ Checking CSV File Availability

CSV files के साथ काम करने से पहले check करना जरूरी है कि file मौजूद है या नहीं, ताकि FileNotFoundError से बचा जा सके।

💻 Example 7: Check CSV File Existence


import os, csv

filename = "students.csv"

if os.path.exists(filename):
    with open(filename, "r") as file:
        reader = csv.reader(file)
        print("CSV Data:")
        for row in reader:
            print(row)
else:
    print("CSV file not found!")
  

Output:
CSV Data:
['Name', 'Age', 'Marks']
['Ravi', '20', '85']
['Anita', '22', '90']


🧾 7️⃣ Example: Display File Statistics

os.stat() function file की detailed information देता है जैसे size, creation time, etc.


import os

stats = os.stat("demo.txt")
print("File Size (bytes):", stats.st_size)
print("Last Modified:", stats.st_mtime)
  

Output:
File Size (bytes): 22
Last Modified: 1731106574.0567296


💬 Interview FAQs

  • Q: What does tell() function do?
    A: It returns the current position of the file pointer.
  • Q: What is the use of seek()?
    A: It repositions the file pointer to the specified location.
  • Q: How can we check if a file exists?
    A: Using os.path.exists("filename").
  • Q: How do we delete a file?
    A: Use os.remove("filename").
  • Q: What is the difference between readlines() and readline()?
    A:
    • readline() → Reads one line at a time.
    • readlines() → Returns all lines as a list.
6️⃣ Reading & Writing Combined Operations (Text + CSV + Binary + Pickling)

📘 Introduction

Python में file operations को दो categories में divide किया जा सकता है: Reading (data पढ़ना) और Writing (data लिखना)। इस chapter में हम text, binary, CSV और pickle files के लिए combined operations समझेंगे।


🧾 1️⃣ Reading & Writing Text Files

Text files में simple human-readable text होता है। इन्हें "r" और "w" modes से खोला जाता है।

💻 Example 1: Read and Write Together


# Write data
with open("textdata.txt", "w") as f:
    f.write("Python File Handling is Fun!\n")
    f.write("Let's learn reading and writing both.")

# Read same file
with open("textdata.txt", "r") as f:
    content = f.read()
    print("File Content:\n", content)
  

Output:
Python File Handling is Fun!
Let's learn reading and writing both.


📊 2️⃣ Reading & Writing CSV Files

CSV files tabular format में data store करती हैं। इन्हें handle करने के लिए csv module का उपयोग किया जाता है।

💻 Example 2: Write and Read CSV File


import csv

# Writing CSV file
with open("students.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age", "Marks"])
    writer.writerow(["Ravi", 20, 85])
    writer.writerow(["Anita", 22, 90])

# Reading CSV file
with open("students.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
  

Output:
['Name', 'Age', 'Marks']
['Ravi', '20', '85']
['Anita', '22', '90']


💾 3️⃣ Reading & Writing Binary Files

Binary files में text नहीं बल्कि raw data (bytes) store होता है, जैसे images, videos, या audio files।

💻 Example 3: Copy Binary File


# Copying an image file
with open("photo.jpg", "rb") as src:
    data = src.read()

with open("photo_copy.jpg", "wb") as dest:
    dest.write(data)

print("Binary file copied successfully!")
  

Output:
Binary file copied successfully!

💡 Binary files को पढ़ते समय text encoding नहीं होती — data bytes format में ही read/write किया जाता है।


🧠 4️⃣ Pickling and Unpickling (Object Serialization)

जब हम किसी Python object (जैसे list, dictionary या class object) को file में store करना चाहते हैं, तो simple text writing से possible नहीं होता। इसके लिए Python pickle module provide करता है।

👉 Pickling → Python object को byte stream में convert कर file में save करना।
👉 Unpickling → File से byte stream को वापस Python object में convert करना।

💻 Example 4: Pickling and Unpickling a Dictionary


import pickle

# Original Python object
student = {"Name": "Ravi", "Age": 20, "Marks": [85, 90, 88]}

# Pickling (Writing object to file)
with open("student.dat", "wb") as f:
    pickle.dump(student, f)

print("Object pickled (saved) successfully!")

# Unpickling (Reading object back)
with open("student.dat", "rb") as f:
    data = pickle.load(f)

print("Unpickled Object:", data)
  

Output:
Object pickled (saved) successfully!
Unpickled Object: {'Name': 'Ravi', 'Age': 20, 'Marks': [85, 90, 88]}

💡 Explanation:
- pickle.dump(obj, file) → object को file में लिखता है (binary format)।
- pickle.load(file) → file से object को वापस Python format में लाता है।


📘 5️⃣ Pickling Multiple Objects

आप एक ही binary file में कई objects को भी pickle कर सकते हैं।

💻 Example 5: Multiple Pickled Objects


import pickle

data1 = {"Name": "Anita", "Marks": 90}
data2 = [10, 20, 30, 40]
data3 = ("Python", "Pickle", "Example")

# Writing multiple objects
with open("multi.dat", "wb") as f:
    pickle.dump(data1, f)
    pickle.dump(data2, f)
    pickle.dump(data3, f)

# Reading back
with open("multi.dat", "rb") as f:
    obj1 = pickle.load(f)
    obj2 = pickle.load(f)
    obj3 = pickle.load(f)

print(obj1)
print(obj2)
print(obj3)
  

Output:
{'Name': 'Anita', 'Marks': 90}
[10, 20, 30, 40]
('Python', 'Pickle', 'Example')


⚙️ 6️⃣ Reading + Writing + Pickling Combined

इस example में हम एक dictionary को pickle करेंगे, फिर read करके modify करेंगे और दोबारा save करेंगे।

💻 Example 6: Modify Pickled Object


import pickle

student = {"Name": "Kiran", "Age": 21, "Marks": 95}

# Pickle (Save)
with open("datafile.dat", "wb") as f:
    pickle.dump(student, f)

# Unpickle (Read)
with open("datafile.dat", "rb") as f:
    data = pickle.load(f)
    print("Before Update:", data)

# Modify and re-pickle
data["Marks"] = 98
with open("datafile.dat", "wb") as f:
    pickle.dump(data, f)

print("After Update Saved Successfully!")
  

Output:
Before Update: {'Name': 'Kiran', 'Age': 21, 'Marks': 95}
After Update Saved Successfully!


💬 Interview FAQs

  • Q: What is Pickling?
    A: Converting a Python object into byte stream and saving it to a file.
  • Q: What is Unpickling?
    A: Retrieving the object back from the byte stream (binary file).
  • Q: Which module is used for pickling?
    A: Python’s built-in pickle module.
  • Q: What are the file modes used for pickling?
    A: "wb" for writing, "rb" for reading.
  • Q: Can we store multiple objects in a single pickle file?
    A: Yes, using multiple pickle.dump() calls.
  • Q: Is pickled data human-readable?
    A: No, it is stored in binary format.
7️⃣ File Exceptions & Error Handling

📘 Introduction

जब हम file operations करते हैं (read/write), तो कभी-कभी errors या exceptions आ सकते हैं — जैसे file का exist न होना, permission denied होना, या data corrupt होना। ऐसे में Python का try-except mechanism program को crash होने से बचाता है।


⚙️ 1️⃣ What is Exception Handling?

Exception handling का मतलब है error को handle करना ताकि program रुके नहीं। Python में errors को handle करने के लिए try, except, else, finally blocks का उपयोग किया जाता है।


try:
    # Risky code
except ExceptionType:
    # Error handling code
else:
    # Runs if no error occurs
finally:
    # Runs always (for cleanup)
  

💻 Example 1: Handling File Not Found


try:
    f = open("unknown.txt", "r")
    data = f.read()
    print(data)
except FileNotFoundError:
    print("Error: File does not exist.")
finally:
    print("Program finished.")
  

Output:
Error: File does not exist.
Program finished.

💡 Explanation:
- अगर file मौजूद नहीं है तो FileNotFoundError raise होता है। - Program crash नहीं होता क्योंकि exception handle कर लिया गया।


📄 2️⃣ Handling Multiple Exceptions

आप एक साथ कई प्रकार के errors handle कर सकते हैं।

💻 Example 2: Multiple Except Blocks


try:
    f = open("demo.txt", "r")
    data = f.read()
    print("File data:", data)
except FileNotFoundError:
    print("Error: File not found.")
except PermissionError:
    print("Error: Permission denied.")
except Exception as e:
    print("Other error:", e)
finally:
    print("Execution completed.")
  

Output:
File data: (content of demo.txt)
Execution completed.

💡 Explanation:
- FileNotFoundError → File नहीं मिली। - PermissionError → File को access करने की अनुमति नहीं। - Exception → सभी बाकी errors को handle करता है।


🧩 3️⃣ Using with open() Safely

with open() block automatically file close कर देता है और error आने पर भी resource leak नहीं होता।

💻 Example 3: Safe File Handling


try:
    with open("students.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("File missing! Please create it first.")
  

Output:
File missing! Please create it first.


📦 4️⃣ Catching IO Errors

IOError तब आता है जब read/write operation में कोई input/output problem होती है।

💻 Example 4: IOError Handling


try:
    f = open("/restricted_folder/data.txt", "w")
    f.write("Testing file write...")
except IOError:
    print("I/O Error: Cannot access the file.")
finally:
    print("I/O operation attempted.")
  

Output:
I/O Error: Cannot access the file.
I/O operation attempted.


🧮 5️⃣ Using Else & Finally

- else: block तब execute होता है जब कोई error नहीं आती। - finally: block हमेशा execute होता है (cleanup tasks जैसे file close करना)।

💻 Example 5: Full Try-Except-Else-Finally Structure


try:
    f = open("example.txt", "w")
    f.write("This is error-free file writing.")
except IOError:
    print("I/O error occurred.")
else:
    print("File written successfully!")
finally:
    f.close()
    print("File closed safely.")
  

Output:
File written successfully!
File closed safely.


🧠 6️⃣ Example – User Input + File Error Handling

इस example में user से file का नाम लिया गया है, और read करने की कोशिश की गई है। अगर file नहीं मिली तो user को नया file बनाने का option दिया जाता है।

💻 Example 6: File Handling with User Input


filename = input("Enter file name: ")

try:
    with open(filename, "r") as f:
        print(f.read())
except FileNotFoundError:
    print("File not found. Creating new file...")
    with open(filename, "w") as f:
        f.write("New file created successfully!")
    print("File created:", filename)
  

Output:
Enter file name: notes.txt
File not found. Creating new file...
File created: notes.txt


⚠️ 7️⃣ Common File Exceptions

ExceptionDescription
FileNotFoundErrorFile नहीं मिली
PermissionErrorAccess permission नहीं है
IOErrorRead/Write error
IsADirectoryErrorजब file path directory हो
ValueErrorInvalid mode या operation

💬 Interview FAQs

  • Q: What is FileNotFoundError?
    A: Raised when the file you try to open does not exist.
  • Q: How can we handle multiple exceptions?
    A: Use multiple except blocks or combine them using tuple syntax.
  • Q: What is the use of finally block?
    A: It always executes, even if an error occurs — mainly for resource cleanup.
  • Q: What is the difference between IOError and OSError?
    A: Both relate to file access issues; IOError is for read/write problems, OSError covers broader system-related errors.
  • Q: How does 'with open()' handle exceptions?
    A: It ensures the file closes automatically, even if an exception occurs.
8️⃣ Command Line Arguments

📘 Introduction

जब Python program को terminal या command prompt से run किया जाता है, तो हम program के साथ कुछ extra values pass कर सकते हैं — इन्हें Command Line Arguments कहा जाता है। Python में इन्हें handle करने के लिए sys module का उपयोग किया जाता है।

👉 Command Line Arguments से हम runtime पर user input दे सकते हैं बिना input() function का उपयोग किए।


⚙️ 1️⃣ Importing sys Module

Command line arguments access करने के लिए Python का sys module import करना पड़ता है। ये arguments एक list के रूप में store होते हैं — sys.argv में।


import sys
print(sys.argv)
  

अगर आप file को इस तरह चलाते हैं:


python myfile.py one two three
  

Output:
['myfile.py', 'one', 'two', 'three']

💡 Note: - sys.argv[0] हमेशा program का नाम होता है। - बाकी elements command line से pass किए गए arguments होते हैं।


🧮 2️⃣ Example: Display All Command Line Arguments


import sys

print("All Arguments:", sys.argv)
print("Number of Arguments:", len(sys.argv))

for i in range(len(sys.argv)):
    print(f"Argument {i}:", sys.argv[i])
  

Command:
python args_demo.py hello world python

Output:
All Arguments: ['args_demo.py', 'hello', 'world', 'python']
Number of Arguments: 4
Argument 0: args_demo.py
Argument 1: hello
Argument 2: world
Argument 3: python


📊 3️⃣ Example: Sum of Two Numbers

Command line arguments string form में आते हैं, इसलिए उन्हें int() या float() में convert करना ज़रूरी है।


import sys

# python sum_args.py 12 8
a = int(sys.argv[1])
b = int(sys.argv[2])
print("Sum =", a + b)
  

Output:
Sum = 20

💡 Note: IndexError avoid करने के लिए पहले argument count check करें।


⚠️ 4️⃣ Example: Safe Command Line Sum with Validation


import sys

if len(sys.argv) != 3:
    print("Usage: python sum_args.py num1 num2")
else:
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    print("Sum =", a + b)
  

Output:
python sum_args.py 5 10 → Sum = 15
python sum_args.py → Usage: python sum_args.py num1 num2


🧮 5️⃣ Example: Factorial Using Command Line Argument


import sys

n = int(sys.argv[1])
fact = 1
for i in range(1, n + 1):
    fact *= i

print("Factorial of", n, "is", fact)
  

Command:
python fact.py 5

Output:
Factorial of 5 is 120


📄 6️⃣ Example: Read File Name from Command Line


import sys

if len(sys.argv) != 2:
    print("Usage: python readfile.py filename")
else:
    filename = sys.argv[1]
    try:
        with open(filename, "r") as f:
            print(f.read())
    except FileNotFoundError:
        print("Error: File not found.")
  

Command:
python readfile.py notes.txt

Output:
(Displays content of notes.txt)


📘 7️⃣ Example: Command Line CSV Reader


import sys, csv

if len(sys.argv) != 2:
    print("Usage: python readcsv.py filename.csv")
else:
    filename = sys.argv[1]
    try:
        with open(filename, "r") as file:
            reader = csv.reader(file)
            for row in reader:
                print(row)
    except FileNotFoundError:
        print("CSV file not found.")
  

Command:
python readcsv.py students.csv

Output:
['Name', 'Age', 'Marks']
['Ravi', '20', '85']
['Anita', '22', '90']


📦 8️⃣ Using sys.argv with len()

len(sys.argv) बताता है कि कितने arguments pass किए गए हैं। इससे validation करना आसान होता है।


import sys

print("Total Arguments Passed:", len(sys.argv))
  

Output:
python test.py 10 20 30
Total Arguments Passed: 4


💬 Interview FAQs

  • Q: What is sys.argv?
    A: A list containing all command-line arguments passed to a Python script.
  • Q: What does sys.argv[0] contain?
    A: It contains the name of the Python script file.
  • Q: How can you check number of arguments?
    A: Using len(sys.argv).
  • Q: Are command-line arguments strings or numbers?
    A: All arguments are strings by default; you must convert them using int() or float().
  • Q: What happens if insufficient arguments are passed?
    A: Python raises an IndexError if you access a non-existent index.