Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Get sorted file names from a directory by creation date in Python
Next article icon

Python - Move Files To Creation and Modification Date Named Directories

Last Updated : 25 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 traversing 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("successfully moved...") 

  

Output:


 


 


Next Article
Get sorted file names from a directory by creation date in Python
author
triposat
Improve
Article Tags :
  • Python
  • Python directory-program
Practice Tags :
  • python

Similar Reads

  • How to get file creation and modification date or time in Python?
    We often need to access various file properties for different purposes. Among the file properties, the creation and modification time of a file are the most commonly used ones. We can achieve the same functionality and use it for various utility purposes, using multiple methods. You can use function
    4 min read
  • Get sorted file names from a directory by creation date in Python
    In this article, we will understand how to retrieve sorted file names from a directory using Python. For this, we would make use of the Python glob library's glob function. There is no need to install this module externally because it is already included with Python. Firstly, The glob function would
    3 min read
  • Python | Move or Copy Files and Directories
    Let's say we want to copy or move files and directories around, but don’t want to do it by calling out to shell commands. The shutil module has portable implementations of functions for copying files and directories. Code #1 : Using shutil module import shutil # Copy src to dst. (cp src dst) shutil.
    3 min read
  • Listing out directories and files in Python
    The following is a list of some of the important methods/functions in Python with descriptions that you should know to understand this article. len() - It is used to count number of elements(items/characters) of iterables like list, tuple, string, dictionary etc. str() - It is used to transform data
    6 min read
  • How to move all files from one directory to another using Python ?
    In this article, we will see how to move all files from one directory to another directory using Python.  In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil m
    2 min read
  • Create temporary files and directories using tempfile
    Python tempfile module allows you to create a temporary file and perform various operations on it. Temporary files may be required when we need to store data temporarily during the program's execution or when we are working with a large amount of data. These files are created with unique names and s
    5 min read
  • Copy all files from one directory to another using Python
    Copying files from one directory to another involves creating duplicates of files and transferring them from one folder to another. This is helpful when organizing files, backing them up, or moving them to different locations on your computer. Let’s explore various methods to do this efficiently. Us
    2 min read
  • Python | Create Archives and Find Files by Name
    In this article, we will learn how to create or unpack archives in common formats (e.g., .tar, .tgz, or .zip) using shutil module. The shutil module has two functions — make_archive() and unpack_archive() — that can exactly be the solution. Code #1 : import shutil shutil.unpack_archive('Python-3.3.0
    3 min read
  • How to Create Directory If it Does Not Exist using Python?
    In this article, We will learn how to create a Directory if it Does Not Exist using Python. Method 1: Using os.path.exists() and os.makedirs() methods Under this method, we will use exists() method takes path of demo_folder as an argument and returns true if the directory exists and returns false if
    2 min read
  • How to List all Files and Directories in FTP Server using Python?
    FTP ( File Transfer Protocol ) is set of rules that computer follows to transfer files across computer network. It is TCP/IP based protocol. FTP lets clients share files. FTP is less secure because of files are shared as plain text without any encryption across the network.  It is possible using pyt
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences