python比较两个txt,将所有不同的行组成新的txt
时间: 2024-10-20 08:10:04 浏览: 27
当然可以。首先,我们需要确保你已经安装了Python,并且你知道两个需要进行比较的.txt文件的路径。
以下是一个简单的Python脚本,它将读取两个.txt文件,找出所有的不同行,并将这些不同的行写入一个新的.txt文件。
```python
def compare_txts(file1_path, file2_path, output_path):
with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2:
lines1 = file1.readlines()
lines2 = file2.readlines()
# 使用集合(set)去除重复的行
line_set1 = set(lines1)
line_set2 = set(lines2)
# 找出并输出不同的行
different_lines = line_set1 - line_set2
with open(output_path, 'w') as outfile:
for line in different_lines:
outfile.write(line)
outfile.write('\n') # 添加换行符,使得每行都单独一行
# 使用函数
compare_txts('path_to_file1.txt', 'path_to_file2.txt', 'output.txt')
```
请将上述代码中的 `'path_to_file1.txt'` 和 `'path_to_file2.txt'` 替换为你的实际文件路径,将 `'output.txt'` 替换为你希望保存新文件的路径。这个脚本会找出两个文件中所有的不同行,并将它们写入一个新的文件中。注意,这个脚本只会找出不同的行,并不会比较文本内容。
这个脚本只适用于两个非常小的文件。如果你的文件非常大,你可能需要使用更高级的工具或者方法来比较文件。此外,这个脚本假设两个文件的格式是相同的,如果有不同的格式,你可能需要先处理或清洗你的文件。
阅读全文
相关推荐


















