• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Automatically Sort and Organize Your Downloads Folder on Linux Using Python By Alpha Nsimba Kasanji

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
If your Downloads folder is always overflowing with random files, and you're constantly digging through it to find what you need - it's time to automate the chaos.
In this tutorial, you'll learn how to create a Python script that automatically organizes your Downloads folder by sorting files into subfolders based on their file types (images, documents, videos, etc.). We'll also show how to run this script automatically at regular intervals using cron.

What You'll Need
A Linux machine (we'll be using Debian-based systems)
Python 3 installed (which comes pre-installed on most distributions)
Basic knowledge of terminal commands


  1. Create Your Python Script
    First, open your terminal and create the Python script:
    touch sort_downloads.py
    chmod +x sort_downloads.py
    This command creates an empty file and makes it executable.


  2. The Script: Sort Files by Extension
    Open the file with a text editor:
    nano ~/sort_downloads.py
    Paste the following Python code:

    !/usr/bin/env python3


    import os
    import shutil
    from pathlib import Path

    Define the Downloads directory


    downloads_dir = Path.home() / "Downloads"

    Define destination directories and file extensions


    categories = {
    "Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp"],
    "Documents": [".pdf", ".docx", ".txt", ".pptx", ".xlsx"],
    "Videos": [".mp4", ".avi", ".mkv", ".mov", ".flv"],
    "Archives": [".zip", ".tar.gz", ".rar"],
    "Audio": [".mp3", ".wav", ".ogg"],
    "Misc": [] # For unrecognized files
    }

    Create subdirectories if they don't exist


    for category in categories:
    folder = downloads_dir / category
    folder.mkdir(exist_ok=True)

    Move files into appropriate folders


    for item in downloads_dir.iterdir():
    if item.is_file():
    moved = False
    for category, extensions in categories.items():
    for ext in extensions:
    if item.name.lower().endswith(ext):
    shutil.move(str(item), str(downloads_dir / category / item.name))
    moved = True
    break
    if moved:
    break
    if not moved:
    shutil.move(str(item), str(downloads_dir / "Misc" / item.name))
    print("Downloads folder organized successfully!")
    Save and exit (CTRL + O, then CTRL + X in nano).


  3. Run the Script
    To test your script, run:
    python3 ~/sort_downloads.py
    Your Downloads folder should now be neatly organized into categories like Images, Documents, Videos, etc.


  4. Automate the Script with Cron
    To keep your folder clean continuously, you can schedule the script to run automatically.
    Open the crontab editor:
    crontab -e
    Add the following line to run the script every hour:
    0 * * * * /usr/bin/python3 /home/yourusername/sort_downloads.py
    Make sure to replace /home/yourusername/ with your actual username. You can find the path to Python with:
    which python3
    Save and exit the editor.

Why This Works
Cross-platform: This script can run on any Linux distro with Python installed.
Customizable: Add more categories and extensions as needed.
Low maintenance: Once set up, it just works quietly in the background.
No clutter: Keeps your Downloads folder clean and manageable.

Conclusion
With just a few lines of Python and a simple cron job, you've turned your chaotic Downloads folder into a well-organized space. This little script saves time, reduces clutter, and makes your workflow more efficient - all without lifting a finger after setup.
Happy automating!


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу