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

yipeiwu_com6年前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);

以上这篇通过python将大量文件按修改时间分类的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python字典排序的方法

python字典排序的方法

python字典怎么排序? 定义一个字典类型 mydict = {2: '小路', 3: '黎明', 1: '郭富城', 4:'周董'} 可分别打印 key和value 看一下数据 按...

Python数组遍历的简单实现方法小结

本文实例总结了Python数组遍历的简单实现方法。分享给大家供大家参考,具体如下: >>> os.__file__.split('\\') ['E:', 'Pyt...

python3的UnicodeDecodeError解决方法

python3的UnicodeDecodeError解决方法

爬虫部分解码异常 response.content.decode() # 默认使用 utf-8 出现解码异常 以下是设计的通用解码 通过 text 获取编码 # 通过...

使用urllib库的urlretrieve()方法下载网络文件到本地的方法

使用urllib库的urlretrieve()方法下载网络文件到本地的方法

概述 见源码 源码 # !/usr/bin/env python # -*- coding:utf-8 -*- """ 图片(文件)下载,核心方法是 urllib.urlre...

深入解析Python中的变量和赋值运算符

深入解析Python中的变量和赋值运算符

Python 变量类型 变量存储在内存中的值。这就意味着在创建变量时会在内存中开辟一个空间。 基于变量的数据类型,解释器会分配指定内存,并决定什么数据可以被存储在内存中。 因此,变量可以...