Using python to categorize a large number of files by modification time

  • 2020-12-20 03:42:03
  • OfStack

The requirements are as follows. I have stored a lot of photos on my hard disk since I was an undergraduate. They were originally classified according to categories. You can right view the attributes of the photo and see its modification date to categorize it. However, the manual classification of more than 10 G photos is still a lot of work, so I want to write a script to complete this task.

The program is mainly to obtain the modification time of the file, including year and month, and create a folder with this name, and then recursively call the way to traverse the entire folder, copy each photo to the corresponding folder.

The program source code is as follows:


#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);


Related articles: