There is a tendency for files to accumulate on the desktop over time, making it difficult to locate the specific files that you want. The purpose of this Python script, “Organize Desktop Files with Python,” is to organize the files that are located on your desktop into folders according to the extensions of the files. By using this script, you will be able to have a more organized desktop and find your files with more ease.
Table of Contents
desktop_sorter.py
Script Usage
To use the script, you will need Python installed on your computer. Once Python is installed, open a command prompt or terminal and navigate to the directory where the script is located. Then, run the following command:
python desktop_sorter.py --desktop_path /path/to/desktop
Replace <path-to-desktop>
with the actual path to your desktop. For example, on Windows, the path could be C:\Users\username\Desktop
, while on Mac, it could be /Users/username/Desktop
.
How The Code Works
Argument Parsing
The script uses argparse
to define and parse command-line arguments.
Specifically, it expects a --desktop_path
argument which specifies the path to the desktop directory.
File Sorting Process
The script defines a mapping (folder_names
) from file extensions to folder names. This mapping determines where each file will be moved based on its extension.
Iterating Over Files
It iterates through all files in the specified desktop directory (desktop_path
).
For each file, it checks if it’s a regular file (not a directory).
Determining Destination Folder
Extracts the file extension using os.path.splitext(file_name)[1]
.
Checks if the file extension exists in folder_names
.
Moving Files
If the file extension corresponds to a folder name in folder_names
, it creates the destination folder if it doesn’t exist.
Moves the file to the appropriate folder based on its extension using shutil.move
.
Main Function
The main
function orchestrates the entire process:
Parses command-line arguments to get the desktop path.
Calls sort_files_on_desktop
with the specified desktop path to sort the files.
By running this script with the --desktop_path
argument pointing to your desktop directory, it will organize the files on your desktop into folders based on their file extensions according to the defined mapping (folder_names
). This helps in keeping the desktop organized and categorizing files by type.
See also: Other useful Python Scripts
Got any queries or feedback? Feel free to drop a comment below!