1. Reading and Writing Text Files
Pehle basic text file read aur write ka example dekhte hain:
# Writing to a text file
with open("sample.txt", "w") as f:
f.write("Hello AIkiPadhai!\n")
f.write("Python file handling is easy.")
# Reading from a text file
with open("sample.txt", "r") as f:
content = f.read()
print(content)
Output:
Hello AIkiPadhai!
Python file handling is easy.
2. Working with CSV Files
csv module ka use structured data handle karne ke liye hota hai.
import csv
# Writing CSV file
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
writer.writerow(["Rahul", 20])
writer.writerow(["Priya", 22])
# Reading CSV file
with open("students.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Output:
['Name', 'Age']
['Rahul', '20']
['Priya', '22']
3. Working with JSON Files
JSON format widely used hai APIs aur web development me.
import json
data = {
"name": "Ravi",
"age": 25,
"skills": ["Python", "AI", "ML"]
}
# Writing JSON file
with open("data.json", "w") as f:
json.dump(data, f)
# Reading JSON file
with open("data.json", "r") as f:
loaded_data = json.load(f)
print(loaded_data)
Output:
{'name': 'Ravi', 'age': 25, 'skills': ['Python', 'AI', 'ML']}
Summary
- Text Files: open(), read(), write()
- CSV Files: csv.reader, csv.writer
- JSON Files: json.load, json.dump