Building an AI-Powered File Organizer with Python and Claude
I hate organizing files, especially the ones that pile up in my Downloads folder. It's like a digital junkyard that keeps growing, making it impossible to find anything when I need it. But what if I could automate this process using AI?
In this tutorial, we'll build a smart file organizer that uses Anthropic's Claude AI to automatically categorize and organize your files. Let's turn that messy Downloads folder into a well-organized directory structure!
You are not limited to using Anthropic's Claude AI. You can use any AI model that can classify files based on their content.
The Problem
Manual organization is time-consuming and often inconsistent. What if we could automate this process using AI?
The Solution
We'll create a Python script that:
- Scans a directory of your choice
- Uses Claude AI to intelligently categorize each file
- Organizes files into appropriate folders based on their content
- Handles duplicates and maintains a clean structure
Prerequisites
Before we dive in, you'll need:
- Python 3.7+
- An Anthropic API key (you can get one from Anthropic's website)
- The following Python packages:
pip install anthropic pathlib
The Code Breakdown
Let's look at the key components of our file organizer:
1. Setting Up the Organizer
class ClaudeFileOrganizer:
def __init__(self):
self.api_key = self._get_api_key()
self.source_dir = self._get_directory()
self.organized_dir = self.source_dir / "organized"
self.client = anthropic.Anthropic(api_key=self.api_key)
This initializes our organizer with:
- User's API key (securely input)
- Source directory to organize
- Output directory for organized files
- Anthropic client for AI classification
2. File Classification with Claude
The magic happens in the classify_file
method:
def classify_file(self, file_info: Dict) -> str:
prompt = f"""
You are a productivity guru! 🧠📚🚀
Based on the following file information, suggest a single appropriate category:
Filename: {file_info['name']}
Type: {file_info['mime_type']}
Created: {file_info['created']}
"""
message = self.client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}]
)
category = message.content[0].text.strip().lower()
return category
This method:
- Takes file metadata as input
- Constructs a prompt for Claude
- Gets an AI-powered category suggestion
- Returns a standardized category name
3. The Organization Process
The main organization logic happens in organize_files
:
- Scans the source directory
- Processes each file
- Creates category folders
- Handles duplicate files
- Moves files to their new homes
# Create category directory
category_dir = self.organized_dir / category
category_dir.mkdir(exist_ok=True)
# Handle duplicates with timestamps
if new_path.exists():
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
new_path = category_dir / f"{file_path.stem}_{timestamp}{file_path.suffix}"
shutil.move(str(file_path), str(new_path))
Smart Features
-
Rate Limiting: The script includes a 5-second delay between API calls to avoid rate limits:
time.sleep(5) # Prevent API rate limiting
-
Progress Tracking: Real-time progress updates keep you informed:
print(f"\rProgress: {processed_files}/{total_files} files processed", end="")
-
Error Handling: Robust error handling ensures the script doesn't crash on issues:
try: # Process file except Exception as e: self.logger.error(f"Error processing file {file_path}: {str(e)}") continue
-
Logging: Comprehensive logging helps track operations and debug issues:
logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler('file_organizer.log'), logging.StreamHandler() ] )
How to Use It
-
Save the script as
file_organizer.py
-
Install required packages:
pip install anthropic pathlib
-
Run the script:
python file_organizer.py
-
Enter your Anthropic API key when prompted
-
Provide the directory path you want to organize
-
Watch as your files get automatically organized!
The Results
Your files will be organized into these categories:
- 📄 documents
- 🖼️ images
- 🎵 audio
- 🎥 video
- 📦 archives
- 💻 code
- 📊 data
- ⬇️ downloads
- 📁 other
Each category gets its own folder, making it easy to find what you need.
Future Improvements
Here are some ways you could enhance the script:
- Add custom category definitions
- Implement file content analysis for better classification
- Add a preview mode to see changes before applying them
- Add support for recursive directory organization
- Create a GUI interface