organize the files of the current directory in python

To organize files in the current directory of a Python program, we can use the os module in combination with various directory and file operations. Here's an example code block that shows how to organize files based on their extensions:

main.py
import os
from pathlib import Path

# Get current directory
dir_path = Path().absolute()

# Iterate over all files in the directory
for file in os.listdir(dir_path):
    # Ignore directories and hidden files
    if os.path.isdir(file) or file.startswith('.'):
        continue

    # Get the file extension
    file_ext = Path(file).suffix

    # Create a new directory for the extension if it doesn't exist
    if not os.path.exists(dir_path / file_ext[1:]):
        os.mkdir(dir_path / file_ext[1:])

    # Move the file to the corresponding directory
    os.rename(dir_path / file, dir_path / file_ext[1:] / file)
617 chars
22 lines

In this code block, we first get the absolute path of the current directory using the pathlib module. We then iterate over all files in the directory (os.listdir()) and ignore directories and hidden files. For each file, we get its extension using pathlib.Path().suffix and create a new directory with that extension name if it doesn't already exist using os.mkdir(). Finally, we move the file to the corresponding directory using os.rename().

This is just one example of how to organize files in Python. There are many other ways and variations depending on your specific requirements.

gistlibby LogSnag