🔹 ফাইল ওপেন করার মোড (File Modes)
| Mode | কাজ |
|---|---|
r | ফাইল পড়া |
w | নতুন করে লেখা (পুরনো ডেটা মুছে যায়) |
a | শেষে ডেটা যোগ করা |
x | নতুন ফাইল তৈরি |
rb | বাইনারি ফাইল পড়া |
wb | বাইনারি ফাইল লেখা |
🔹 with statement (Best Practice)
with ব্যবহার করলে ফাইল নিজে থেকেই বন্ধ হয়ে যায়।
with open("data.txt", "r") as file:
content = file.read()
print(content)👉 আলাদা করে file.close() লাগবে না।
🔹 লাইন ধরে ফাইল পড়া
with open("data.txt", "r") as file:
for line in file:
print(line.strip())🔹 read(), readline(), readlines()
file = open("test.txt", "r")
print(file.read()) # পুরো ফাইল
print(file.readline()) # এক লাইন
print(file.readlines()) # সব লাইন লিস্ট আকারে
file.close()🔹 ফাইলে ডেটা লেখা (Write)
with open("output.txt", "w") as file:
file.write("Hello Python\n")
file.write("Advanced File Handling")⚠️ w মোড পুরনো ডেটা মুছে দেয়।
🔹 ফাইলে ডেটা যোগ করা (Append)
with open("output.txt", "a") as file:
file.write("\nNew line added")🔹 ফাইল পয়েন্টার (tell & seek)
with open("data.txt", "r") as file:
print(file.tell()) # বর্তমান অবস্থান
file.seek(5) # ৫ নম্বর পজিশনে যাওয়া
print(file.read())🔹 ফাইল আছে কিনা চেক করা
import os
if os.path.exists("data.txt"):
print("File exists")
else:
print("File not found")🔹 রিয়েল লাইফ উদাহরণ: লগ ফাইল তৈরি
from datetime import datetime
with open("log.txt", "a") as file:
file.write(f"Login time: {datetime.now()}\n")👉 এই পদ্ধতি ওয়েব অ্যাপ, সফটওয়্যারে ব্যাপকভাবে ব্যবহৃত হয়।
🔹 বাইনারি ফাইল পড়া ও লেখা
# বাইনারি ফাইল লেখা
with open("image.jpg", "rb") as img:
data = img.read()
with open("copy.jpg", "wb") as new_img:
new_img.write(data)❌ সাধারণ ভুল
- ফাইল বন্ধ না করা
- ভুল mode ব্যবহার করা
- file path ভুল দেওয়া
- বড় ফাইল
read()দিয়ে পড়া
🏁 উপসংহার
এই পর্বে তুমি শিখলে—
✅ Advanced file modes
✅ with statement
✅ read / write / append
✅ file pointer
✅ binary file handling
✅ real-life example







