网络编程
位置:首页>> 网络编程>> Python编程>> 通过python将大量文件按修改时间分类的方法

通过python将大量文件按修改时间分类的方法

作者:AlexAcce  发布时间:2023-04-11 00:26:03 

标签:python,文件,分类

需求是这样的,我从本科到现在硬盘里存了好多照片,本来是按类别分的,有一天,我突然想,要是能按照时间来分类可能会更好。可以右键查看照片的属性,看它的修改日期,从而分类,但是十几个G的照片手动分类工作量还是很大的,所以想着写个脚本程序来完成这一个工作。

程序主要是获取文件的修改时间,包括年和月,并以此为名创建文件夹,再用递归调用的方式遍历整个文件夹,将每一张照片拷贝到相应的文件夹下。

程序源码如下:


#coding:utf-8
import os
import sys
import os.path
import time
from shutil import Error
from shutil import copystat
from shutil import copy2

path_str = r"D:\pic";

def copy_file(src_file, dst_dir):
if os.path.isdir(dst_dir):
 pass;
else:
 os.makedirs(dst_dir);
print(src_file);
print(dst_dir);
copy2(src_file, dst_dir)

def walk_file(file_path):
for root, dirs, files in os.walk(file_path, topdown=False):
 for name in files:
  com_name = os.path.join(root, name);
  t=os.stat(com_name);
  copy_path_str = path_str+r"\year"+str(time.localtime(t.st_mtime).tm_year)+r"\month"+str(time.localtime(t.st_mtime).tm_mon);
  print(copy_path_str);
  copy_file(com_name,copy_path_str);
 for name in dirs:
  walk_file(name);

walk_file(path_str);

来源:https://blog.csdn.net/Alex1syyl/article/details/53997054

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com