import shutil
import os
path1 = "D:/PYQT5/9-17/labels/train/" #主文件夹
path2 = "D:/PYQT5/9-17/labels/val/"
final_dir = "D:/PYQT5/9-17/labels/final/"
i = 0
def filenames1(path1,path2): #以path1路径为主进行判断,获得第一个文件夹下的文件路径
filename1 = []
for root,name,files in os.walk(path1):
for file in files:
for root2,name2,files2 in os.walk(path2):
if file in files2:
filename1.append(path1+file)
return filename1
def filenames2(path1,path2): #以path1路径为主进行判断,获得另一个路径下文件路径
filename2 = []
for root,name,files in os.walk(path1):
for file in files:
for root2,name2,files2 in os.walk(path2):
if file in files2:
filename2.append(path2+file)
return filename2
file1 = filenames1(path1,path2)
file2 = filenames2(path1,path2)
# print(file1)
# print(file2)
def searchfile(file1,file2): #改变文件,筛选
for f1 in file1:
for f2 in file2:
if f1[27:]==f2[25:]: #注意这里获得文件名,27是D:/PYQT5/9-17/labels/train/的长度
# print(1)
with open(f1,'r') as s1:
a1 = s1.readlines()
b1 = change(a1)
print(a1,f1)
print(b1)
# s1.close()
with open(f2,'r') as s2:
a2 = s2.readlines()
b2 = change(a2)
print(a2)
for l in range(len(b2)):
if b2[l] not in b1:
lien = b2[l].strip()
print(lien)
with open(f1,"a") as s1:
s1.write('\n'+lien)
# s1.close()
def change(a): #对获得的列表内字符进行改变
b = []
for i in a:
i = i.strip() #删除去"202\n"里的\n
b.append(i)
return b
searchfile(file1,file2)
path_final = "D:/PYQT5/9-17/labels/final" #最后保存文件的路径
for item in file1:
shutil.copy(item, path_final) #将文件复制到设定的文件夹中
# shutil.move(item, path1) #将文件移动到设定的文件夹中
通过利用shutil和os库获得两个文件夹下同名文件,然后分别用filenames1、filenames2获得写入列表。
之后在searchfile里分别对文件内容进行对比,如果相同最后将file1中文件copy至新的文件夹内,如果不同则将file2不同的部分移入file1里,然后copy至新的文件夹里。