The Ultimate Guide to Organizing Files and Directories in Ubuntu: Tips, Tricks, and Python Script

In today’s world, we deal with an overwhelming amount of data on our computers. From photos and videos to documents and spreadsheets, the data keeps piling up, and we often find ourselves struggling to keep it organized. One way to make our lives easier is to organize our files and directories by month and year. In this blog post, we’ll show you how to do it in Ubuntu using a simple Python script.

Step 1: Whitelist Acceptable Directories

The first step is to define a whitelist of acceptable directories that you want to organize by month and year. This ensures that you don’t accidentally move important system files or directories. You can define the whitelist in the Python script using the os.path.join and os.path.expanduser functions to specify the full path to the directories.

Step 2: Get the Current Month and Year

The next step is to get the current month and year using the datetime module. This will be used to create the directory for the current month and year and move the files and directories into it.

Step 3: Create the Directory for the Current Month and Year

Using the os.makedirs function, you can create the directory for the current month and year. If the directory already exists, the function will not create a new one.

Step 4: Move Files and Directories to the Current Month and Year Directory

Using the shutil.move function, you can move all the files and directories from the specified directory to the current month and year directory. The function checks if the item is a file or directory and moves it accordingly. It also checks if the item is the year directory or a subdirectory of the year directory and skips it.

Step 5: Automate the Process

To make your life easier, you can automate the process using the cron job scheduler. You can set the script to run at the beginning of each month to organize the files and directories automatically.

  1. Open a terminal window and type the following command: crontab -e. This will open the crontab file in your default text editor.
  2. Add the following line at the end of the file to schedule the script to run at the beginning of each month:
    • 0 0 1 * * /usr/bin/python3 /path/to/your/python/script.py Replace /path/to/your/python/script.py
    • with the full path to the Python script you created in the previous steps.
  3. Save and exit the crontab file.

Now, the script will run automatically at the beginning of each month, organizing your files and directories by month and year.

The Code:

#!/usr/bin/env python3

import os
import shutil
import datetime
import logging

# Get the current user's home directory
home_dir = os.path.expanduser('~')

# Define a whitelist of acceptable directories using the home directory variables
whitelist = [os.path.join(home_dir, 'Documents'),
             os.path.join(home_dir, 'Downloads'),
             os.path.join(home_dir, 'Dropbox'),
             os.path.join(home_dir, 'Music'),
             os.path.join(home_dir, 'Pictures'),
             os.path.join(home_dir, 'Videos')]

# Get the previous month and current year
now = datetime.datetime.now()
previous_month = (now.replace(day=1) - datetime.timedelta(days=1)).strftime('%B')
current_year = now.strftime('%Y')

# Configure logging to write messages to the system log
logging.basicConfig(level=logging.INFO)

# Loop through each directory in the whitelist
for dir_to_clean in whitelist:
    # Check if the directory exists and is not a system directory
    if os.path.exists(dir_to_clean) and '/usr/' not in os.path.abspath(dir_to_clean):
        # Create the directory for the previous month and current year if it doesn't exist
        current_dir = os.path.join(dir_to_clean, current_year, previous_month)
        if not os.path.exists(current_dir):
            os.makedirs(current_dir)

        # Move all files and directories from the directory to the previous month and current year directory
        for item_name in os.listdir(dir_to_clean):
            item_path = os.path.join(dir_to_clean, item_name)
            if os.path.isfile(item_path) or os.path.islink(item_path):
                shutil.move(item_path, current_dir)
            elif os.path.isdir(item_path):
                # Check if the item is the year directory or a subdirectory of the year directory
                if item_name == current_year:
                    continue
                if os.path.abspath(item_path).startswith(os.path.abspath(current_dir)):
                    continue
                # Move the item to the previous month and current year directory
                shutil.move(item_path, os.path.join(current_dir, item_name))

        # Log a message to indicate that the cleanup is complete
        logging.info(f'{dir_to_clean} cleaned up and organized by month and year.')
    else:
        # Log a message to indicate that the directory does not exist
        logging.info(f'{dir_to_clean} does not exist, skipping.')

Organizing files and directories by month and year is an easy and effective way to keep your computer tidy and make it easier to find your files. With this step-by-step guide, you can quickly and easily organize your files and directories in Ubuntu.