【Python】去重合并两个文本文件内容
准备工作
假设有两个文本文件file1.txt和file2.txt,内容分别为:
file1.txt
apple
banana
cherry
file2.txt
banana
cherry
date
实现步骤
- 读取文件内容
使用Python的open()函数读取文件内容,并使用read().splitlines()或逐行读取以构建列表。 - 合并并去重
将两个列表合并后,使用集合(set)去重,因为集合是一个无序且不包含重复元素的集合。 - 输出结果
将去重后的结果写回文件或打印到控制台。
示例代码
# 读取文件内容
with open('file1.txt', 'r') as file1, open('file2.txt', 'r') as file2:
lines1 = file1.read().splitlines()
lines2 = file2.read().splitlines()
# 合并并去重
all_lines = set(lines1 + lines2)
# 写入新文件或打印
with open('merged_unique.txt', 'w') as outfile:
for line in sorted(all_lines): # 排序输出,可选
outfile.write(line + '\n')
# 或者直接打印到控制台
print('\n'.join(sorted(all_lines)))



