Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีลบบรรทัดซ้ำในไฟล์ข้อความด้วย Python

ใช้ set เพื่อเก็บบรรทัดที่เคยเจอ แล้วเขียนเฉพาะบรรทัดที่ไม่ซ้ำลงไฟล์ใหม่

ตัวอย่าง: ลบบรรทัดซ้ำใน bar.txt บันทึกลง foo.txt

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)
    if line not in lines_seen:
        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)

เนื้อหา bar.txt

A cow is an animal.
A cow is an animal.
A buffalo too is an animal.
Lion is the king of jungle.

ผลลัพธ์ foo.txt

A cow is an animal.
A buffalo too is an animal.
Lion is the king of jungle.

วิธีนี้เหมาะสำหรับไฟล์ขนาดเล็ก สำหรับไฟล์ใหญ่ควรใช้ itertools หรือ database