问题描述
我想以一种有效的方式做的是使用 glob 仅在关联的主文件夹和子文件夹中搜索文件名,而不是按照我当前的代码遍历所有主文件夹/子文件夹。我需要它然后与我拥有的主文件夹和子文件夹匹配,如果匹配,则复制文件。我有有效的代码,但效率非常低,每次搜索都必须遍历所有文件夹/子文件夹。代码如下;此时,main_folder 和searchdate 是lists.filenames_i_want,也是我要匹配的列表。有什么办法可以让它直接进入文件夹/子文件夹,例如,如果我将其作为 CSV 输入提供?
import itertools
import glob
import shutil
from pathlib import Path
filenames_i_want = Search_param
main_folder=locosearch
searchfolder= Search_date
TargetFolder = r'C:\ELK\LOGS\XX\DEST'
for directory,folder in itertools.product(main_folder,searchfolder):
files = glob.glob('Z:/{}/{}/asts_data_logger/*.bz2'.format(directory,folder))
for f in files:
current_path = Path(f)
cpn = current_path.name
if current_path.name in filenames_i_want:
print(f"found target file: {f}")
shutil.copy2(f,TargetFolder)
解决方法
我创建了一个列并使用这些字段创建了一个绝对路径,然后使用元组遍历每一行并使用shutil进行复制
TargetFolder = r'C:\ELK\LOGS\ATH\DEST'
for row in df.itertuples():
search = row.Search
try:
shutil.copy2(search,TargetFolder)
except Exception as e:
print(e)