赞
踩
在做Python项目时,需要实现很多小功能。
这里需要实现对比两个文件夹下所有txt内容是否相同,呼唤ChatGPT…
代码如下:
设置文件夹1的路径folder1 = ‘’
设置文件夹2的路径folder2 = ‘’
运行即可。
import os def compare_folders(folder1, folder2): # 获取文件夹中的所有txt文件 txt_files1 = [f for f in os.listdir(folder1) if os.path.isfile(os.path.join(folder1, f)) and f.endswith('.txt')] txt_files2 = [f for f in os.listdir(folder2) if os.path.isfile(os.path.join(folder2, f)) and f.endswith('.txt')] # 遍历文件夹中的每个txt文件,逐一比较内容 for f1, f2 in zip(txt_files1, txt_files2): with open(os.path.join(folder1, f1), 'r') as file1, open(os.path.join(folder2, f2), 'r') as file2: content1 = file1.read() content2 = file2.read() # 判断两个文件的内容是否相同 if content1 == content2: print(f"{f1} and {f2} are identical") else: print(f"{f1} and {f2} are different") # 需要修改的地方 folder1 = '' folder2 = '' compare_folders(folder1=folder1,folder2=folder2)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。