বিভিন্ন মোডে ফাইল খোলা (r, w, a, r+)

ফাইল হ্যান্ডলিং - পাইথন ৩ (Python 3) - Computer Programming

257

পাইথনে ফাইল খোলার জন্য বিভিন্ন মোড ব্যবহার করা হয়, যা আমাদের ফাইলের সাথে কাজ করার পদ্ধতি নির্ধারণ করে। নিচে প্রতিটি মোডের বিবরণ দেওয়া হলো:

১. r (Read Mode)

  • বর্ণনা: এই মোডে ফাইলটি পড়ার জন্য খোলা হয়। যদি ফাইলটি না পাওয়া যায়, তবে FileNotFoundError হবে।
  • ব্যবহার: শুধুমাত্র ফাইলের বিষয়বস্তু পড়তে ব্যবহৃত হয়।

উদাহরণ:

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

২. w (Write Mode)

  • বর্ণনা: এই মোডে ফাইলটি লেখার জন্য খোলা হয়। যদি ফাইলটি আগে থেকে বিদ্যমান থাকে, তবে পুরনো তথ্য মুছে ফেলা হয় এবং নতুন তথ্য লেখা হয়।
  • ব্যবহার: ফাইল তৈরি বা পুরনো ফাইলের তথ্য প্রতিস্থাপন করতে ব্যবহৃত হয়।

উদাহরণ:

with open('example.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This will overwrite the file.")

৩. a (Append Mode)

  • বর্ণনা: এই মোডে ফাইলটি লেখার জন্য খোলা হয় এবং নতুন তথ্য ফাইলের শেষে যোগ করা হয়। পূর্ববর্তী তথ্য মুছে ফেলা হয় না।
  • ব্যবহার: একটি বিদ্যমান ফাইলে নতুন তথ্য যোগ করতে ব্যবহৃত হয়।

উদাহরণ:

with open('example.txt', 'a') as file:
    file.write("Adding a new line.\n")

৪. r+ (Read and Write Mode)

  • বর্ণনা: এই মোডে ফাইলটি পড়ার এবং লেখার জন্য খোলা হয়। যদি ফাইলটি বিদ্যমান না হয়, তবে FileNotFoundError হবে। এটি পূর্ববর্তী তথ্যের সাথে কাজ করতে সক্ষম।
  • ব্যবহার: ফাইলের তথ্য পড়তে এবং সেই সঙ্গে লেখার জন্য ব্যবহৃত হয়।

উদাহরণ:

with open('example.txt', 'r+') as file:
    content = file.read()
    print("Current content:", content)
    file.write("Appending this line after reading.\n")

মোডগুলোর সংক্ষেপিত তুলনা:

মোডবর্ণনাপূর্ববর্তী তথ্যের অবস্থা
rশুধুমাত্র পড়ার জন্যকিছুই পরিবর্তন হয় না
wলেখার জন্য (পুরনো তথ্য মুছে যায়)পুরনো তথ্য মুছে যায়
aনতুন তথ্য যোগ করার জন্যপুরনো তথ্য অপরিবর্তিত থাকে
r+পড়া এবং লেখা উভয়ের জন্যপুরনো তথ্য অপরিবর্তিত থাকে

উদাহরণস্বরূপ পূর্ণ প্রোগ্রাম

# Writing to a file
with open('example.txt', 'w') as file:
    file.write("This is the first line.\n")

# Reading from the file
with open('example.txt', 'r') as file:
    print("Reading the file:")
    print(file.read())

# Appending to the file
with open('example.txt', 'a') as file:
    file.write("This line is added later.\n")

# Reading again to see the changes
with open('example.txt', 'r') as file:
    print("After appending:")
    print(file.read())

# Reading and writing to the file
with open('example.txt', 'r+') as file:
    content = file.read()
    print("Current content:", content)
    file.write("Adding this line after reading.\n")

# Final read
with open('example.txt', 'r') as file:
    print("Final content:")
    print(file.read())

সংক্ষেপে:

পাইথনে বিভিন্ন মোডে ফাইল খোলা হয়, যা আমাদের ফাইলের সাথে কাজ করার পদ্ধতি নির্ধারণ করে। r, w, a, এবং r+ মোডগুলির মাধ্যমে আমরা পড়া, লেখা, এবং সংযোজন করতে পারি। এই সব মোড আমাদের ফাইল পরিচালনায় সর্বাধিক সুবিধা দেয়।

Content added By
Promotion

Are you sure to start over?

Loading...