代码示例:
import os
# 读取文件1的内容
with open('file1.txt', 'r') as file1:
content1 = file1.readlines()
# 读取文件2的内容
with open('file2.txt', 'r') as file2:
content2 = file2.readlines()
# 提取两个文件中共同的行
common_rows = set(content1) & set(content2)
# 将共同的行分别写入两个单独的文件
with open('common_file1.txt', 'w') as common_file1:
for row in common_rows:
if row in content1:
common_file1.write(row)
with open('common_file2.txt', 'w') as common_file2:
for row in common_rows:
if row in content2:
common_file2.write(row)
解释说明:
open()
函数读取文件1和文件2的内容并保存到两个变量中。set()
函数将文件1和文件2的内容分别转换成集合,并使用 &
运算符获取两个集合中共同的元素。这里使用集合是因为它能够自动去重,确保唯一性。common_file1.txt
和 common_file2.txt
文件中。需要注意的是,此代码示例仅适用于文本文件。如果需要比较二进制文件,需要使用其他方法。