-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorganize.py
More file actions
108 lines (94 loc) · 4.29 KB
/
organize.py
File metadata and controls
108 lines (94 loc) · 4.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import os
import shutil
from tqdm import tqdm
def organize_desktop():
# Define desktop path (works for Windows/macOS/Linux)
desktop_Name="Desktop"
desktop_path = os.path.join(os.path.expanduser("~"), desktop_Name)
#returns an error message if desktop path wasn't found
if not os.path.exists(desktop_path):
print("Desktop Path not available....")
return
else:
pass
# Define file type categories
file_categories = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".webp"],
"Documents": [".pdf", ".docx", ".doc", ".xlsx", ".pptx", ".txt", ".csv"],
"Videos": [".mp4", ".mov", ".avi", ".mkv", ".flv", ".wmv"],
"Audio": [".mp3", ".wav", ".ogg", ".m4a", ".flac"],
"Archives": [".zip", ".rar", ".7z", ".tar", ".gz"],
"Executables": [".exe", ".msi", ".dmg", ".pkg", ".sh"],
"Code": [".py", ".js", ".html", ".css", ".cpp", ".java", ".json",".cs",".pkt"],
"Sprites":[".ase",".pxo",".aseprite",".kra"],
"Shortcuts":[".lnk"],
"Others": [] # For any unrecognized file types
}
# Create folders if they don't exist
for folder in file_categories.keys():
folder_path = os.path.join(desktop_path, folder)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
# Get all files (skip dirs/hidden files)
files = [f for f in os.listdir(desktop_path)
if not (f.startswith('.') or os.path.isdir(os.path.join(desktop_path, f)))]
# Organize files
# Add progress bar
for file in tqdm(files, desc="Organizing files", unit="file"):
file_path = os.path.join(desktop_path, file)
# Skip directories and hidden files (like .DS_Store on macOS)
# if os.path.isdir(file_path) or file.startswith('.'):
# continue
# Get file extension
_, file_ext = os.path.splitext(file)
file_ext = file_ext.lower() # Ensure case-insensitive matching
# Determine the category
moved = False
for category, extensions in file_categories.items():#loops thru category and extensions to move files away
if file_ext in extensions:
dest_folder = os.path.join(desktop_path, category)
# if is_file_locked(file_path)==False:
# shutil.move(file_path, os.path.join(dest_folder, file))
# moved = True
# break
# elif is_file_locked(file_path)==True:
# print(file," is locked..Moving to next file...")
if not is_file_locked(file_path):
try:
shutil.move(file_path, os.path.join(dest_folder, file))
moved=True
except Exception as e:
print(f"Error moving file{file}:{e}")
else:
print(f"{file} is locked. Moving to next file...")
break
# If no category found, move to "Others"
if not moved:
dest_folder = os.path.join(desktop_path, "Others")
if not is_file_locked(file_path):#is_file_locked(file_path)==False:
shutil.move(file_path, os.path.join(dest_folder, file))
else :
print(f"[Others]{file}, is locked..Moving to next file..." )
print("Desktop files organized successfully!")
# def is_file_locked(filepath):
# try:
# with open (filepath,'r+',encoding='utf-8') as f:
# pass
# return False
# except (IOError,PermissionError,FileNotFoundError):
# return True
def is_file_locked(filepath):
"""Check if a file is locked by trying to open it in read-only mode."""
try:
with open(filepath, 'rb') as f: # Binary read mode (least intrusive)
pass
return False # File is NOT locked
except (PermissionError, IOError) as e:
# Only return True for specific errors (not FileNotFoundError)
if "Permission denied" in str(e).lower():
return True
return False # Other errors (e.g., file not found) are treated as unlocked
except Exception:
return False # Default to unlocked for unexpected errors
if __name__ == "__main__":
organize_desktop()