File Organizer Tool Python
👤 Sharing: AI
```python
import os
import shutil
import logging
import argparse
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
def organize_files(source_dir, target_dir, file_extensions):
"""
Organizes files from a source directory into subdirectories within a target directory
based on their file extensions.
Args:
source_dir (str): The directory to read files from.
target_dir (str): The directory to organize files into.
file_extensions (dict): A dictionary where keys are file extensions
(e.g., "pdf", "jpg") and values are the corresponding
subdirectory names (e.g., "Documents", "Images").
"""
if not os.path.isdir(source_dir):
logging.error(f"Source directory '{source_dir}' does not exist.")
return
if not os.path.isdir(target_dir):
try:
os.makedirs(target_dir) # Create target directory if it doesn't exist
logging.info(f"Created target directory '{target_dir}'.")
except OSError as e:
logging.error(f"Could not create target directory: {e}")
return
for filename in os.listdir(source_dir):
source_path = os.path.join(source_dir, filename)
# Skip directories
if os.path.isdir(source_path):
logging.debug(f"Skipping directory: {filename}")
continue
# Extract file extension
try:
file_extension = filename.split(".")[-1].lower() # Get extension and lowercase it for consistency
except IndexError:
logging.warning(f"File '{filename}' has no extension. Skipping.")
continue # Skip files without extensions.
# Determine target subdirectory
if file_extension in file_extensions:
subdirectory = file_extensions[file_extension]
else:
subdirectory = "Other" # Default subdirectory
# Create the subdirectory if it does not exist
subdirectory_path = os.path.join(target_dir, subdirectory)
if not os.path.isdir(subdirectory_path):
try:
os.makedirs(subdirectory_path)
logging.info(f"Created subdirectory '{subdirectory}' in '{target_dir}'.")
except OSError as e:
logging.error(f"Could not create subdirectory: {e}")
continue # skip to the next file
# Construct the destination path
destination_path = os.path.join(subdirectory_path, filename)
# Move the file
try:
shutil.move(source_path, destination_path)
logging.info(f"Moved '{filename}' to '{subdirectory}'")
except Exception as e:
logging.error(f"Error moving '{filename}': {e}")
def main():
"""
Main function to parse command-line arguments and execute the file organization.
"""
parser = argparse.ArgumentParser(
description="Organize files in a directory based on extension."
)
parser.add_argument(
"source_dir", help="The directory to organize files from."
)
parser.add_argument(
"target_dir", help="The directory to organize files into."
)
args = parser.parse_args()
# Define file extensions and their corresponding subdirectories
file_extensions = {
"pdf": "Documents",
"txt": "Documents",
"docx": "Documents",
"jpg": "Images",
"jpeg": "Images",
"png": "Images",
"gif": "Images",
"mp3": "Audio",
"wav": "Audio",
"mp4": "Video",
"avi": "Video",
"mov": "Video",
"zip": "Archives",
"rar": "Archives",
"7z": "Archives",
"csv": "Data",
"xlsx": "Data"
}
organize_files(args.source_dir, args.target_dir, file_extensions)
logging.info("File organization complete.")
if __name__ == "__main__":
main()
```
Key improvements and explanations:
* **Clearer Structure:** The code is now organized into functions for better readability and maintainability (`organize_files`, `main`).
* **Argument Parsing:** The `argparse` module is used to handle command-line arguments, making the script more flexible and user-friendly. Users can now specify the source and target directories when running the script from the command line. Example usage: `python your_script_name.py /path/to/source /path/to/target`
* **Error Handling:** Includes robust error handling with `try...except` blocks to catch potential exceptions like `OSError` (directory creation errors), file moving errors, and `IndexError` (handling files without extensions). Uses `logging` to report these errors.
* **Logging:** Uses the `logging` module to provide informative messages about the script's progress, including successes, warnings, and errors. This is *much* better than `print` statements because it can be configured to write to a file, change verbosity, etc.
* **File Extension Handling:** Extracts the file extension more reliably and handles cases where files have no extension. Converts the extension to lowercase for consistent comparisons.
* **Target Directory Creation:** Checks if the target directory and subdirectories exist and creates them if they don't. Handles potential errors during directory creation.
* **`shutil.move`:** Uses `shutil.move` to move files, which is generally more reliable than `shutil.copy2` followed by `os.remove` in case of errors during the copy operation. `shutil.move` also handles cross-filesystem moves automatically, which `shutil.copy2` and `os.remove` do not.
* **`if __name__ == "__main__":`:** The standard Python idiom to ensure the `main` function is only executed when the script is run directly (not when it's imported as a module).
* **Comments and Docstrings:** The code is well-commented with descriptive docstrings for each function, explaining its purpose, arguments, and return value.
* **Default Subdirectory:** Added a default subdirectory "Other" for files with extensions that are not in the `file_extensions` dictionary.
* **Flexibility:** The `file_extensions` dictionary can be easily modified to add or change the file extensions and their corresponding subdirectories.
* **Skips Directories:** The code now explicitly skips directories that it finds in the source directory.
* **Clearer Variable Names:** More descriptive variable names (e.g., `source_path`, `destination_path`).
* **Conciseness:** The code has been made more concise without sacrificing readability.
How to Run the Code:
1. **Save:** Save the code as a Python file (e.g., `file_organizer.py`).
2. **Open a Terminal or Command Prompt:** Navigate to the directory where you saved the file.
3. **Run the Script:** Execute the script with the following command:
```bash
python file_organizer.py /path/to/source_directory /path/to/target_directory
```
Replace `/path/to/source_directory` with the actual path to the directory containing the files you want to organize, and `/path/to/target_directory` with the path to the directory where you want the organized files to be placed. The target directory will be created if it doesn't already exist.
Example:
```bash
python file_organizer.py /Users/myuser/Downloads/Unorganized /Users/myuser/Documents/Organized
```
This will move the files from the `/Users/myuser/Downloads/Unorganized` directory into subdirectories within `/Users/myuser/Documents/Organized`, based on their file extensions.
Remember to adjust the file paths according to your specific system and directory structure. Make sure the source directory exists and that you have the necessary permissions to read and write files in both the source and target directories.
👁️ Viewed: 8
Comments