有些時候我們需要按照excel中的名單查找出文件夾中的文件(word,pdf,txt,png,jpg)都可以,
如excel名單為:(我們需要篩選出的文件是x1,x2)
原始文件夾為:(原始文件夾包含x1,x3)
篩選出的文件夾為:(篩選出來的只包含x1)
import os import numpy as np import pandas as pd import shutil file_path=r'C:\Users\17360\Desktop\test' #文件路徑 filename_path=r'C:\Users\17360\Desktop\test1.xlsx' #文件列表 filelist=os.listdir(file_path) #獲取文件夾中的文件名稱 file_name=pd.read_excel(filename_path) #讀取所需文件列表 for file in filelist: print(file) file_name file_name.shape[0] file_name['count']=0 #定義新的一列count,用於計數 for file in filelist: m=file_name.shape[0] #表格的行數 olddir=os.path.join(file_path,file) #每一個文件路徑 for i in range(m): if str(file_name['name'][i]) in file: #尋找對應的文件名 F=r"C:\Users\17360\Desktop\myfiles_filter" #新文件夾名稱(先建好) newdir=os.path.join(F,file) shutil.copy(olddir,newdir) #復制到新文件夾中 file_name['count'][i]=file_name['count'][i]+1 #計數 print(file) #打印出文件名,為了看它是不是在運行 else: continue file_name.to_excel(r'C:\Users\17360\Desktop\file_name_count.xlsx') #保存新的文件列表,可以統計每個文件出現的次數
有問題歡迎留言哦~~