工业生产视觉机台依据产品二维码生成图片,都存档在一个文件夹内,导致一个文件夹下图片太多(几十万计),文件夹都打开不了
可不可以依据图片创立日期自动归档到对应日期的文件夹里
导入os库,shutil库
os.walk(文件夹) 遍历文件夹
os.stat(filename)[获取文件的创建时间戳]
将时间戳转成日期时间
os.mkdir(时间文件夹名)
shutil.copy(源文件,目标文件)
详细注解如下:
import os,time,shutil
path = r'd:\java' #换成你要处理的文件夹
for file in os.listdir(path): #遍历整个文件夹
fullname = os.path.join(path,file) #文件的全路径名称
if not os.path.isfile(fullname): #如果不是文件,跳过以下操作
continue
t = time.gmtime(os.path.getmtime(fullname)) #获取文件创建日期
datepath = f'{t.tm_year}-{t.tm_mon:02}-{t.tm_mday:02}' #日期文件夹统一为: yyyy-mm-dd
newpath = os.path.join(path, datepath) #新的日期文件夹
if not os.path.isdir(newpath): #如果日期文件夹不存在,则创建它
os.mkdir(newpath)
shutil.move(fullname, newpath) #移动文件到日期文件夹
path改成你的文件夹
import os
import shutil
import time
path = "d:\\test\\"
os.chdir(path)
files = list(os.listdir())
for file in files:
try:
create_time = os.path.getctime(file)
struct_time = time.localtime(create_time)
year = struct_time.tm_year
month = struct_time.tm_mon
day = struct_time.tm_mday
folder_name = str.format("{}-{}-{}", year, month, day)
if not os.path.isdir(folder_name):
os.mkdir(folder_name)
print("已创建"+folder_name+"文件夹")
shutil.move(file, folder_name)
except:
pass