ให้เราตั้งชื่อไฟล์ข้อความที่กำหนดเป็น bar.txt
เราใช้วิธีการจัดการไฟล์ใน python เพื่อลบบรรทัดที่ซ้ำกันในไฟล์ข้อความหรือฟังก์ชันของ python ไฟล์ข้อความหรือฟังก์ชันต้องอยู่ในไดเร็กทอรีเดียวกันกับไฟล์โปรแกรมหลาม โค้ดต่อไปนี้เป็นวิธีหนึ่งในการลบรายการที่ซ้ำกันในไฟล์ข้อความ bar.txt และเอาต์พุตจะถูกเก็บไว้ใน foo.txt ไฟล์เหล่านี้ควรอยู่ในไดเร็กทอรีเดียวกันกับไฟล์สคริปต์ python มิฉะนั้นจะไม่ทำงาน
ไฟล์ bar.txt มีดังต่อไปนี้
A cow is an animal. A cow is an animal. A buffalo too is an animal. Lion is the king of jungle.
ตัวอย่าง
รหัสด้านล่างลบบรรทัดที่ซ้ำกันใน bar.txt และเก็บไว้ใน foo.txt
# This program opens file bar.txt and removes duplicate lines and writes the
# contents to foo.txt file.
lines_seen = set() # holds lines already seen
outfile = open('foo.txt', "w")
infile = open('bar.txt', "r")
print "The file bar.txt is as follows"
for line in infile:
print line
if line not in lines_seen: # not a duplicate
outfile.write(line)
lines_seen.add(line)
outfile.close()
print "The file foo.txt is as follows"
for line in open('foo.txt', "r"):
print line
ผลลัพธ์
ไฟล์ foo.txt มีดังต่อไปนี้
A cow is an animal. A buffalo too is an animal. Lion is the king of jungle.