【Python】去重合并两个文本文件内容

作者: admin 分类: Python 发布时间: 2024-10-15 09:28

准备工作

假设有两个文本文件file1.txtfile2.txt,内容分别为:

file1.txt

apple
banana
cherry

file2.txt

banana
cherry
date

实现步骤

  1. 读取文件内容
    使用Python的open()函数读取文件内容,并使用read().splitlines()或逐行读取以构建列表。
  2. 合并并去重
    将两个列表合并后,使用集合(set)去重,因为集合是一个无序且不包含重复元素的集合。
  3. 输出结果
    将去重后的结果写回文件或打印到控制台。

示例代码

# 读取文件内容
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)))

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

标签云
站点地图 Sitemap
申请 友情链接
网站运行