Skip to content

Commit

Permalink
Merge pull request #11 from priyanka350/FileOrgSnippet
Browse files Browse the repository at this point in the history
Addition of File organizer snippet
  • Loading branch information
UTSAVS26 authored Oct 5, 2024
2 parents 5d62618 + 6e5d3d0 commit 9c75730
Show file tree
Hide file tree
Showing 3 changed files with 184 additions and 0 deletions.
66 changes: 66 additions & 0 deletions Tests/test_file_organizer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#test_file_organizer.py

import unittest
import os
import tempfile
import shutil
from Snippets.File_Organizer.file_organizer import organize_files_by_type

class TestOrganizeFilesByType(unittest.TestCase):

def setUp(self):
# Create a temporary directory for testing
self.test_dir = tempfile.mkdtemp()
# Create a few files for testing
self.files_to_create = {
'image1.jpg': 'image content',
'document1.pdf': 'pdf content',
'video1.mp4': 'video content',
'music1.mp3': 'music content',
'script1.py': 'print("Hello World")',
'archive1.zip': 'zip content',
'unrecognized_file.txt': 'unrecognized content',
'font1.ttf': 'font content', # Font file
'font2.otf': 'font content', # Font file
'system_file.exe': 'executable content', # System file
'system_file.dll': 'dll content', # System file
}
for filename, content in self.files_to_create.items():
with open(os.path.join(self.test_dir, filename), 'w') as f:
f.write(content)

def tearDown(self):
# Remove the temporary directory after the tests
shutil.rmtree(self.test_dir)

def test_organize_files(self):
# Test case for normal behavior
organize_files_by_type(self.test_dir)

# Check if the files were moved to the correct folders
for category in ['Images', 'Documents', 'Videos', 'Music', 'Scripts', 'Archives', 'Fonts', 'System']:
category_path = os.path.join(self.test_dir, category)
self.assertTrue(os.path.exists(category_path), f"{category_path} should exist.")

# Check specific files in their corresponding folders
self.assertTrue(os.path.exists(os.path.join(self.test_dir, 'Images', 'image1.jpg')))
self.assertTrue(os.path.exists(os.path.join(self.test_dir, 'Documents', 'document1.pdf')))
self.assertTrue(os.path.exists(os.path.join(self.test_dir, 'Videos', 'video1.mp4')))
self.assertTrue(os.path.exists(os.path.join(self.test_dir, 'Music', 'music1.mp3')))
self.assertTrue(os.path.exists(os.path.join(self.test_dir, 'Scripts', 'script1.py')))
self.assertTrue(os.path.exists(os.path.join(self.test_dir, 'Archives', 'archive1.zip')))
self.assertTrue(os.path.exists(os.path.join(self.test_dir, 'Fonts', 'font1.ttf')))
self.assertTrue(os.path.exists(os.path.join(self.test_dir, 'Fonts', 'font2.otf')))
self.assertTrue(os.path.exists(os.path.join(self.test_dir, 'System', 'system_file.exe')))
self.assertTrue(os.path.exists(os.path.join(self.test_dir, 'System', 'system_file.dll')))

# Check that the unrecognized file is still in the root folder
self.assertTrue(os.path.exists(os.path.join(self.test_dir, 'unrecognized_file.txt')))

def test_invalid_folder(self):
# Test case for invalid input
with self.assertRaises(ValueError):
organize_files_by_type('invalid_path')

if __name__ == '__main__':
unittest.main()
4 changes: 4 additions & 0 deletions pysnippets/File_Organizer/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# __init__.py

# This file allows the snippets folder to be treated as a package.
# It can be empty or used to expose certain functions for easy imports.
114 changes: 114 additions & 0 deletions pysnippets/File_Organizer/file_organizer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# file_organizer.py

import os
import shutil

def organize_files_by_type(folder_path):
"""
Organizes files in the specified folder by file type, moving them into categorized subfolders.
Args:
folder_path (str): The path to the folder to organize.
Returns:
None
Example:
If you have a folder with images, documents, and videos mixed together, this function will
move them into 'Images', 'Documents', 'Videos', etc., subfolders based on their extensions.
Raises:
ValueError: If the folder_path does not exist.
"""
if not os.path.exists(folder_path):
raise ValueError(f"The folder path '{folder_path}' does not exist.")

# Define file categories and their extensions
file_categories = {
'Images': [
'.jpg', '.jpeg', '.png', '.gif', '.bmp',
'.tiff', '.tif', '.svg', '.webp', '.raw',
'.heif', '.heic', '.ico', '.ai', '.eps',
'.indd', '.pdf', '.jfif', '.exif'
],
'Documents': [
'.pdf', '.docx', '.doc', '.txt', '.xls',
'.xlsx', '.pptx', '.ppt', '.csv', '.odt',
'.rtf', '.wps', '.xml', '.html', '.md',
'.tex', '.epub', '.xps', '.mobi', '.wps',
'.numbers', '.key', '.pages'
],
'Videos': [
'.mp4', '.mov', '.avi', '.mkv', '.wmv',
'.flv', '.webm', '.mpeg', '.mpg', '.3gp',
'.mpv', '.m4v', '.f4v', '.vob', '.rm',
'.rmvb', '.asf', '.m2ts', '.ts', '.divx',
'.xvid'
],
'Music': [
'.mp3', '.wav', '.flac', '.aac', '.ogg',
'.m4a', '.wma', '.opus', '.alac', '.aiff',
'.mid', '.midi', '.ra', '.3gp', '.dsf',
'.dff', '.wv', '.cda'
],
'Archives': [
'.zip', '.rar', '.tar', '.gz', '.7z',
'.bz2', '.xz', '.iso', '.dmg', '.jar',
'.tar.gz', '.tgz', '.z', '.ace', '.cab',
'.lzh', '.arj'
],
'Scripts': [
'.py', '.js', '.html', '.css', '.c',
'.cpp', '.rb', '.php', '.java', '.sh',
'.go', '.swift', '.pl', '.perl', '.sql',
'.dart', '.kotlin', '.xml', '.yaml',
'.json', '.bat', '.vbs', '.asp'
],
'Fonts': [
'.ttf', '.otf', '.woff', '.woff2', '.eot',
'.svg', '.fnt', '.fon', '.apk'
],
'System': [
'.exe', '.dll', '.sys', '.bin', '.iso',
'.img', '.sh', '.cmd', '.bat'
]
}


# Create category folders if they don't exist
for category in file_categories:
category_path = os.path.join(folder_path, category)
if not os.path.exists(category_path):
os.makedirs(category_path)

# Organize files
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)

# Skip directories
if os.path.isdir(file_path):
continue

# Get file extension
_, file_extension = os.path.splitext(filename)

# Move the file to the appropriate category folder
moved = False # Flag to check if the file was moved
for category, extensions in file_categories.items():
if file_extension.lower() in extensions:
shutil.move(file_path, os.path.join(folder_path, category, filename))
print(f"Moved: {filename} -> {category}")
moved = True
break

# If the file type was not recognized, print a message
if not moved:
print(f"Unrecognized file type for: {filename}. File not moved.")

# Example usage
if __name__ == "__main__":
folder_to_organize = r"path_to_the_folder" # Replace with the actual folder path
try:
organize_files_by_type(folder_to_organize)
except ValueError as e:
print(e)

0 comments on commit 9c75730

Please sign in to comment.