Automating File Movement on your system

Imagine a situation like this:You have a folder containing files of multiple types like txt, mp3 etc. You decide to clean up this mess and organize them in a way that images are in one folder and songs in another. Will you be moving them as per file type, i.e. number of moves = number of files . No, I’ll not be doing this :).

This task could be automated by writing this python script which can automatically create a separate directory and move files in their respective destinations.

Please note that you need to setup Python 2 on your system.The script makes use of the module named os which allows us to use OS-specific functionalities.Please note that you need to setup Python on your system before all this can be done. For that, follow these steps:

1) Download the Python from here; https://www.python.org/downloads/

(I’ll prefer 2.7 as it’s a stable build)

2) Install it. Go to C:( where windows reside and Get the path to your python folder (It’ll be something like C:\Python27)

3) Go to My computer (or This pc), go to advanced system settings, search for a variable path there and click on edit.

4) A box will appear with path, scroll the cursor to the already existing path till the end and add ;C:\Python27 (i.e. ; and then the path to your python folder in C drive).

5) Click Save or OK. Create a folder with name Pyprog(or anything else) in your C:\, here we’ll be storing all our python programs, open cmd and type cd C:\Pyprog and then for running a file called first.py (same every python program with an extension .py), run python first.py.

Python code Direct linkhttps://ide.geeksforgeeks.org/9bY2Mm

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ptyhon program to organize files of a directory
import os
import sys
import shutil
  
# This function organizes contents of sourcePath into multiple
# directories using the file types provided in extensionToDir
def OrganizeDirectory(sourcePath, extensionToDir):
    if not os.path.exists(sourcePath):
        print ("The source folder '" + sourcePath +
              "' does not exist!!\n")
    else:
        for file in os.listdir(sourcePath):
            file = os.path.join(sourcePath, file)
  
            # Ignore if its a directory
            if os.path.isdir(file):
                continue
  
            filename, fileExtension = os.path.splitext(file)
            fileExtension = fileExtension[1:]
  
            # If the file extension is present in the mapping
            if fileExtension in extensionToDir:
  
                # Store the corresponding directory name
                destinationName = extensionToDir[fileExtension]
                destinationPath = os.path.join(sourcePath, destinationName)
  
                # If the directory does not exist
                if not os.path.exists(destinationPath):
                    print ("Creating new directory for `" + fileExtension +
                          "` files, named - `" + destinationName + "'!!")
  
                    # Create a new directory
                    os.makedirs(destinationPath)
  
                # Move the file
                shutil.move(file, destinationPath)
  
def main():
  
    if len(sys.argv) != 2:
        print "Usage: <program> <source path directory>"
        return
  
    sourcePath = sys.argv[1]
  
    extensionToDir = {}
    extensionToDir["mp3"] = "Songs"
    extensionToDir["jpg"] = "Images"
  
    print("")
    OrganizeDirectory(sourcePath, extensionToDir)
  
if __name__ == "__main__":
    main()

chevron_right


ekta1

Notice in the above image, two new folders named Images and Songs are created on executing the script and the files with mps and jpg extensions are now inside the requireds

Please note the paths mentioned in the above post are according to a general system, you should change paths according to our requirements and do the classification, but the important point is then changing the current working directory which is done using os.chdir(). Also, more if statements can be added pertaining to different file types.

About the author: Ekta is a  very active contributor on Geeksforgeeks. Currently studying at Delhi Technological University.She has also made a Chrome extention for  www.geeksquiz.com to practise mcqs randomly.She can be reached at  github.com/Ekta1994

If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks.



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.