我有一个脚本,应该比较文件夹和子文件夹中的文件。新的文件应该在以后被复制。这是我用来创建列表的函数。
def fullNames(source):
matches = []
for root, dirnames, filenames in os.walk(source):
for filename in filenames:
if filename.endswith('.xlsx'):
matches.append(os.path.join(root, filename))
return matches
这个函数返回的列表是这样的。
list1 = ['C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-18\\file1.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-18\\file2.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-18\\file3.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-18\\file4.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-18\\file5.xlsx']
list2 = ['C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-17\\file1.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-17\\file2.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-17\\file3.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-17\\file4.xlsx']
为了比较文件,我必须比较每个文件的基名。
list1_short = [os.path.basename(file) for file in list1]
list2_short = [os.path.basename(file) for file in list2]
result = [item for item in list1_short if item not in list2_short]
result
Out[134]: ['file5.xlsx']
这样做是可行的,但我需要返回该文件的完整路径,而不是基名。有人知道如何解决这个问题吗?
这将是我想要的结果。
['C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-18\\file5.xlsx']
你可以直接去掉 list2_short
实际上,你可以通过改变获得结果的方式来实现。
list1 = ['C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-18/file1.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-18/file2.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-18/file3.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-18/file4.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-18/file5.xlsx']
list2 = ['C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-17/file1.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-17/file2.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-17/file3.xlsx',
'C:/Users/langma/Desktop/EDI/Downloadfolder/EDI_2020-05-17/file4.xlsx']
existing_names = [os.path.basename(item) for item in list2]
missing_files = [item for item in list1 if os.path.basename(item) not in existing_names]
你可以通过改变你获得结果的方式来做到这一点。
result = [list1[i] for i in range(len(list1_short)) if list1_short[i] not in list2_short]
list1_short = [os.path.basename(file) for file in list1]
list2_short = [os.path.basename(file) for file in list2]
missing_files=[]
for i,item in enumerate(list1_short):
if item not in list2_short:
missing_files.append(list1[i])