Skip to content
Related Articles

Related Articles

Improve Article

Python – Move Files To Creation and Modification Date Named Directories

  • Difficulty Level : Easy
  • Last Updated : 13 Jul, 2021

We all understand how crucial it is to manage files based on their creation and modification dates. So, in this article, we will try to build a Python script that would move all of your files to new directories based on their creation and modification dates. Basically, it will look for directories and, if any are found, it will extract all the files from that folder, delete that folder, and then arrange them by creation date.

Folder in use:

The picture shows that all the files and folders are not correctly handled. This script would first extract all the files from the directories, such as the one titled Hey. Then it will sort all the files chronologically.

Here, we’ll use some of Python’s most important modules, such as shutil, glob, and so on. Here’s some more information about modules:



  • glob: The glob module is used to find files/pathnames that match a pattern. It is also expected that, based on benchmarks, it would match pathnames quicker than previous techniques.
  • shutil: The Python Shutil module offers various methods for performing high-level operations on files and groups of files. It is one of Python’s standard utility modules. This module aids in the automation of the copying and removing of files and folders.

Approach

  • To change the directory and move to the directory where you wish to place all your files based on the modification date, use the os.chdir function.
  • To list all the folders and files, use the os.listdir function.
  • To get the current working directory, use the os.getcwd method.
  • Run a loop to go over all the files within and outside the directories.
  • For storing all the file instances, use the glob.glob function. It will take the file name or file path and search for all the files present inside it.

Syntax: 

glob.glob(any_file_name or file_path+”\\”*) # 

  • We may simply move files from one location to another by using the shutil.move method. Pass the file name which is to be moved and the path where to be moved.

Syntax:

shutil.move(file to be moved, Path where file is to be moved)

  • After removing the files from the folder, use the shutil.rmtree methods to remove the folder. Pass the file name to be removed in shutil.rmtree function.

Syntax:

shutil.rmtree(file to be remove/delete)

  • Set a loop once more to go through all the files.
  • Use time.gmtime to retrieve all the data about a file’s creation and modifications in the structural form.
  • Then, one by one, extract the Year, Month, and Day.
  • Run an If condition to see if that folder has already been created; if not, create it using the file’s creation date as the name.
  • Finally, using the shutil.move function, move all the files one by one to the newly formed folder.

Program: 

Python3




# Import the following modules
import os
import time
import shutil
import datetime
import glob
  
  
# Change the directory and jump to the location
# where you want to arrange the files
os.chdir(r"C:\Users\Dell\Downloads\FireShot")
  
# List the directories and make a list
all_files = list(os.listdir())
  
# Get the current working directory
outputs = os.getcwd()
  
# Run a loop for traversing through all the 
# files in the current directory
for files in all_files:
    try:
        
        # Jump to the directories files
        inputs = glob.glob(files+"\\*")
          
        # Now again run a loop for travering through
        # all the files inside the folder
        for ele in inputs:
            
            # Now, move the files one-by-one
            shutil.move(ele, outputs)
          
        # After extracting files from the folders, 
        # delete that folder
        shutil.rmtree(files)
    except:
        pass
  
# Again run a loop for traversing through all the
# files in the current directory
for files in os.listdir('.'):
      
    # Get all the details of the file creation 
    # and modification
    time_format = time.gmtime(os.path.getmtime(files))
      
    # Now, extract only the Year, Month, and Day
    datetime_object = datetime.datetime.strptime(str(time_format.tm_mon), "%m")
      
    # Provide the number and find the month
    full_month_name = datetime_object.strftime(
        "%b")
      
    # Give the name of the folder
    dir_name = full_month_name + '-' + \
        str(time_format.tm_mday) + "-" + \
        str(time_format.tm_year)
  
    # Check if the folder exists or not
    if not os.path.isdir(dir_name):
         
        # If not then make the new folder
        os.mkdir(dir_name)
    dest = dir_name
      
    # Move all the files to their respective folders
    shutil.move(files, dest)
      
print("Suceessfully moved...")

Output:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :