File I/O in Python

Introduction

File I/O का मतलब होता है File से data लेना (Input) और File में data लिखना (Output)

जब हम program run करते हैं, तो data temporary memory (RAM) में store होता है।
लेकिन अगर हमें data को future के लिए save करना हो, तो हमें file का use करना पड़ता है।

File क्या होती है

File एक storage unit होती है, जिसमें data permanently store किया जाता है।

जैसे:

  • Text files (.txt)
  • CSV files (.csv)
  • Log files

File I/O क्यों जरूरी है

  • Data को permanently save करने के लिए
  • Large data को manage करने के लिए
  • Records maintain करने के लिए
  • Real-life applications (banking, login, reports) में

File open करना

Python में file को open करने के लिए open() function का उपयोग किया जाता है।

file = open("file_name.txt", "mode")

File Modes

ModeMeaning
“r”read mode
“w”write mode
“a”append mode
“r+”read + write

Example: File open करना

file = open("data.txt", "r")

यह file को read mode में open करता है।

File close करना

File use करने के बाद उसे close करना जरूरी होता है।

file.close()

Real-life समझ

मान लो आप एक notebook खोलते हो:

  • open() → notebook खोलना
  • read/write → पढ़ना या लिखना
  • close() → notebook बंद करना

with statement (Better तरीका)

File को safely handle करने के लिए with statement का use किया जाता है।

with open("data.txt", "r") as file:
print(file.read())

यह automatically file को close कर देता है।

File I/O कैसे काम करता है

  1. File को open किया जाता है
  2. Data read या write किया जाता है
  3. File को close किया जाता है

Real-life Example: Data save करना

with open("student.txt", "w") as file:
file.write("Rahul")

Explanation
यह program student name को file में save करता है।

Real-life Example: Data read करना

with open("student.txt", "r") as file:
data = file.read()
print(data)

Common mistakes

  1. file close करना भूल जाना
  2. wrong mode use करना
  3. file path गलत देना

Mini Program

name = input("Enter your name: ")
with open("data.txt", "w") as file:
file.write(name)
print("Data saved successfully")

Summary

File I/O Python में data को file के माध्यम से read और write करने की process है।
यह concept real-world applications में बहुत महत्वपूर्ण है।

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top