This page looks best with JavaScript enabled

Python - Directory Cleanup

 ·  ☕ 5 min read  ·  🐺 Devoalda

Introduction

This is a script to automate cleanups in any directory. It will move files into folders according to the file extension.

Why?

A clean home/project directory allows us to be able to work productively, without spending much time searching for the particular document/file we need.

This is a simple script to help you clean your directory in seconds

Caution

Dependencies

Code

Imports

This is a python script, we will be using modules os and shutil. First of all, create a new script called script.py, and import the modules required for this

1
2
3
4
#!/usr/bin/env python

import os
import shutil

Notice the first line #!/usr/bin/env python. This is called a shebang. It allows us to run the script as an executable, with the command

1
./script.py

Without the shebang, we will need to use the full command

1
python3 script.py

Defining Main

This step is optional, although it will make the code look cleaner

1
2
3
4
5
def main():
	print('Hello, World!')

if __name__ == "__main__":
    main()

This is how I usually start my code, you will be able to run your code now with the command

1
2
./script.py
 Output: Hello,World!

Defining a dictionary

A dictionary has a key, value pair, similar to a JSON file structure. In this script, we will create a dictionary of File type(Key) and File Extensions (Value).

Insert the following above the line def main():

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
DIRECTORIES_DICTIONARY = {
    'Document': ['.doc','.docx','.pdf','.log','.txt','.rtf','.asp','.aspx','.csv','.html','.css','.js','.xml','.xls'],
    'Folder': [],
    'Audio' : ['.aif','.m3u','mp3','flac','.mpa','.wav','.m4a'], 
    'Video' : ['.mp4','.flv','.mov','.vob'], 
    'Image' : ['.jpg','.jpeg','.png'],
    'Zip' : ['.zip', '.7z', '.tar.gz', '.deb', '.rpm'], 
    'Executables': ['.apk','.exe','.jar'], 
    'Others': []
    }

You are able to expand this dictionary by adding your own file types and file extensions in a similar structure.

Creating folders based on directory key

In def main():, add the following lines

1
2
3
4
5
6
7
DIRECTORIES= []

for dir in DIRECTORIES_DICTIONARY:
	if not os.path.isdir(dir):
	    print("Creating Directory '{}'".format(dir))
	    os.mkdir(dir)
	DIRECTORIES.append(dir)

Note the indentation of the lines!

When you run the script, you will see new folders being created in your directory

Moving file to correct directories

Append the following lines to your main function

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
file_moved_counter = 0
file_list = os.listdir('.')

for file in file_list:
	if 'directory_cleanup' not in file and file not in DIRECTORIES:
	    # Check if file is a folder first
	    if os.path.isdir(file):
		shutil.move(file, './Folder/{}'.format(file))
		file_moved_counter += 1
	else:
		print('Current File: ' + file + '\n')
		filename, file_extension = os.path.splitext(file)
		for dir in DIRECTORIES_DICTIONARY:
		    if file_extension in DIRECTORIES_DICTIONARY[dir]:
			os.rename(file, './'+dir+'/'+ file)
			print('MOVED FILE: ' + file + '\n')  
			file_moved_counter += 1

#Moving files with unknown file extensions to Others folder
new_file_list = os.listdir('.')
for file in new_file_list:
	if 'directory_cleanup' not in file and file not in DIRECTORIES:
	    os.rename(file, './Others/'+ file)
	    file_moved_counter += 1

print('Files Organized!\nTotal file moved: ' + str(file_moved_counter))

These lines will move files to their folder based on their file extensions, and move undefined extensions to the ‘Others’ directory.

In this script, I’ve used both modules os and shutil to move files to show the difference in syntax for each of the modules.

Running the script

1
./script.py

To test the script, you should add/create files with any extensions in the same directory as your script. Upon running the script, you should see all your files moved and categorized according to their file extensions.

Tips

  • I usually create a project folder for any scripts that I create, and run the script in the folder. This prevents any unwanted modifications to any directory.
  • Note that indentations in a python script is very important.
  • This script is useful in certain directories, like Documents or Downloads, as it categorizes those files accordingly and cleans the directory.

Summary

Thats it! You have yourself a cleanup script that you can use to clean any directory you want! The full code is below, do take a look if you are facing any problems!

Full Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#!/usr/bin/env python

#Done By: Devoalda
#Downloads Directory Cleanup

import os
import shutil

DIRECTORIES_DICTIONARY = {
    'Document': ['.doc','.docx','.pdf','.log','.txt','.rtf','.asp','.aspx','.csv','.html','.css','.js','.xml','.xls'],
    'Folder': [],
    'Audio' : ['.aif','.m3u','mp3','flac','.mpa','.wav','.m4a'], 
    'Video' : ['.mp4','.flv','.mov','.vob'], 
    'Image' : ['.jpg','.jpeg','.png'],
    'Zip' : ['.zip', '.7z', '.tar.gz', '.deb', '.rpm'], 
    'Executables': ['.apk','.exe','.jar'], 
    'Others': []
    }

def main():
    file_moved_counter = 0
    file_list = os.listdir('.')
    DIRECTORIES= []

    for dir in DIRECTORIES_DICTIONARY:
        if not os.path.isdir(dir):
            print("Creating Directory '{}'".format(dir))
            os.mkdir(dir)
        DIRECTORIES.append(dir)
    
    for file in file_list:
        if 'directory_cleanup' not in file and file not in DIRECTORIES:
            # Check if file is a folder first
            if os.path.isdir(file):
                shutil.move(file, './Folder/{}'.format(file))
                file_moved_counter += 1
            else:
                print('Current File: ' + file + '\n')
                filename, file_extension = os.path.splitext(file)
                for dir in DIRECTORIES_DICTIONARY:
                    if file_extension in DIRECTORIES_DICTIONARY[dir]:
                        os.rename(file, './'+dir+'/'+ file)
                        print('MOVED FILE: ' + file + '\n')  
                        file_moved_counter += 1
    
    #Moving files with unknown file extensions to Others folder
    new_file_list = os.listdir('.')
    for file in new_file_list:
        if 'directory_cleanup' not in file and file not in DIRECTORIES:
            os.rename(file, './Others/'+ file)
            file_moved_counter += 1
    
    print('Files Organized!\nTotal file moved: ' + str(file_moved_counter))

if __name__ == "__main__":
    main()

Credits

Broom icon icon by Icons8
Share on

Devoalda
WRITTEN BY
Devoalda
Technophile