পাইথন ফাইল হ্যান্ডলিং ব্যবহার করে টেক্সট ফাইল থেকে ডুপ্লিকেট লাইন সরিয়ে নতুন ফাইলে সংরক্ষণ করা যায়। নিচে একটি সম্পূর্ণ উদাহরণ দেওয়া হলো।
ইনপুট ফাইল (bar.txt)
A cow is an animal. A cow is an animal. A buffalo too is an animal. Lion is the king of jungle.
পাইথন কোড
lines_seen = set() # ইতিমধ্যে দেখা লাইনগুলো রাখার সেট
outfile = open('foo.txt', 'w')
infile = open('bar.txt', 'r')
print("The file bar.txt is as follows")
for line in infile:
print(line, end='')
if line not in lines_seen: # ডুপ্লিকেট নয়
outfile.write(line)
lines_seen.add(line)
outfile.close()
infile.close()
print("\nThe file foo.txt is as follows")
for line in open('foo.txt', 'r'):
print(line, end='')
আউটপুট (foo.txt)
A cow is an animal. A buffalo too is an animal. Lion is the king of jungle.
ব্যাখ্যা
set()ব্যবহার করে ইতিমধ্যে প্রসেস করা লাইনগুলো ট্র্যাক করা হয়েছে — O(1) লুকআপ।- লাইন যদি সেটে না থাকে, তবে আউটপুট ফাইলে লিখা হয় এবং সেটে যোগ করা হয়।
- অরডার সংরক্ষণ থাকে (প্রথম حدوثই রাখা হয়)।
উন্নত সংস্করণ (with স্টেটমেন্ট)
with open('bar.txt', 'r') as infile, open('foo.txt', 'w') as outfile:
seen = set()
for line in infile:
if line not in seen:
outfile.write(line)
seen.add(line)
with ব্লক ব্যবহার করলে ফাইল অটোমেটিক্যালি ক্লোজ হয়, এক্সেপশন হলে ও।