Sử dụng set để theo dõi các dòng đã thấy, ghi các dòng duy nhất ra file mới.
File đầu vào: bar.txt
A cow is an animal. A cow is an animal. A buffalo too is an animal. Lion is the king of jungle.
Code xử lý
lines_seen = set() # Lưu các dòng đã gặp
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: # Không trùng lặp
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='')
File đầu ra: foo.txt
A cow is an animal. A buffalo too is an animal. Lion is the king of jungle.
Cải tiến (Python 3, context manager)
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)
Lưu ý
- Giữ nguyên thứ tự dòng xuất hiện đầu tiên.
- So sánh chính xác bao gồm ký tự xuống dòng.
- Với file lớn, cân nhắc dùng
line.strip()nếu muốn bỏ qua khoảng trắng.