Python | Arrange the files in directories according to extensions

In this article, we will learn how to arrange the files in different directories according to their extensions. When you have a lot of files with different extension than you can simply use the script for your help.

Below is the Python implementation –





import os  # Using system functions
import shutil # Moving file to different folders.
# Changing the folder location.
cwd = os.getcwd()
# For listing files from the folder.
l = [f for f in os.listdir(cwd) if os.path.isfile(f)] 
l2 = []
# Get the extension of file from list l.
for  value in l:
    s = value.split('.')[1
print(l, l2)
# We remove duplicate values from 
# list l2 and checks if directory 
# exists otherwise we create new one
for extension in set(l2):
    dirname = extension 
    if os.path.exists(cwd+'\'+extension):
# We use zip function and list l and
# l2 passed as arguments.
# If extension in file is same and
# file not exists then we move the file.
for files, extension in zip(l, l2):
    if extension in files:
        if os.path.exists(cwd+'\'+extension+'\'+files):
            shutil.move(cwd+'\'+files, cwd+'\'+extension)
        print(extension, files)
    else :


Files Not Arranged:

Files Arranged:


['', 'mydata.pdf', 'python.exe', 'resume.doc'] ['py', 'pdf', 'exe', 'doc']
pdf mydata.pdf
exe python.exe
doc resume.doc

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.