Python程序:复制文件夹中修改日期排名前100的图片
以下是一个示例程序,可以实现您的需求:
import os
import shutil
src_dir = 'G:/pictures'
dst_dir = 'G:/data'
for folder_name in os.listdir(src_dir):
folder_path = os.path.join(src_dir, folder_name)
if os.path.isdir(folder_path):
# 获取文件夹下所有文件的修改时间并排序
file_times = [(os.path.join(folder_path, file_name), os.path.getmtime(os.path.join(folder_path, file_name))) for file_name in os.listdir(folder_path)]
file_times.sort(key=lambda x: x[1], reverse=True)
# 复制前100个文件到目标文件夹
for i in range(min(100, len(file_times))):
src_file, _ = file_times[i]
dst_file = os.path.join(dst_dir, folder_name, os.path.basename(src_file))
if not os.path.exists(os.path.dirname(dst_file)):
os.makedirs(os.path.dirname(dst_file))
shutil.copy2(src_file, dst_file)
该程序首先遍历源目录下的所有文件夹,对于每个文件夹:
- 获取其中所有文件的修改时间并排序
- 复制修改时间最新的前100个文件到目标目录下同名的文件夹中
其中 shutil.copy2 函数可以复制文件并保留文件的元数据(如修改时间等)。
原文地址: https://www.cveoy.top/t/topic/obNR 著作权归作者所有。请勿转载和采集!