Organizing Files Using Python

Working Smarter. Not Harder.

Devarshi Patel
2 min readFeb 19, 2021

There are 2.5 quintillion bytes of data created each and every day- and it’s only increasing with the accelerated growth rate of the Internet of Things. Over the last two years alone 90 percent of the data in the world was generated.

There are 18 zeros in a quintillion. Just FYI. You really don’t need a CS background to be blown away by these facts. You can find similarly incogitable facts about the Internet in this Forbes article.

This entry isn’t really jumping into this potential ‘datageddon’, but I think these facts are important to know as we venture into the digital age. Well, after reading the article I went to take a look at my data; the things I download and create on a daily basis like jpg’s, docs, pdf’s, Avi's, XML's, etc…

I’d realized that as I’m constantly adding to that data stockpile, seldom do I ever bother to organize my data (tedious labor). This didn’t end well for me after I wasted 25 minutes trying to find an old .py file for a project. A quarter of an hour of my life gone just like that. I thought of it as a 25-minute sentence for being a slob. Just like an ex-convict (extended metaphor), I’d vowed to turn my life around (from manually organizing files like a neanderthal).

Prerequisite: basic python knowledge, directory tree, file paths, error-handling,

TLDR: Iterate thru the files in a folder, get a file’s extension (ext); if a folder with the ext-name exists, move the file there; otherwise, create a folder with the ext-name and move the file there. It also accounts for a possible FileNotFoundError.

Method Referencing:

OS Module

os.chdir(destination_directory) — — — — (go to)/change specified directory

os.getcwd() — — — — return the current working directory (the one ur in)

os.listdir(_directory_) — — — — list all files and subdirectories in _directory_

os.ext.splitext(_filename_) — — — — returns a list of 2 strings; ie. cat.jpg → [‘cat’, ‘.jpg’]; [1] of this list is ‘.jpg’; [1:] of ‘.jpg’ → ‘jpg’

os.path.isdir(_dirName_) — — — — returns boolean value if _dirName_ is a folder in the cwd (current working directory; the one ur in)

os.makedirs(_dirName_) — — — — makes a folder named ‘_dirName_’

Shutil Module

shutil.move(oldPath, newPath) — — — — pretty self explanatory tbh. Make sure that you add the filename and extension to the end of the new and old path. Ex. ‘cat.jpg’ → shutil.move(“old/path/cat.jpg”, “new/path/cat.jpg”)

Btw: if you run this program in a directory (folder) that has no files to organize, it will output: “No files to move broski.” thanks to the try-except.

--

--