This repository has been archived by the owner on Feb 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_organizer_logic.py
56 lines (47 loc) · 2.18 KB
/
file_organizer_logic.py
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
import os
import sys
import shutil
from datetime import datetime
import file_organizer_log as log
# Function to organize files by date
def organize_files_by_date(folder_path):
base_path = folder_path
for filename in os.listdir(base_path):
if os.path.isfile(os.path.join(base_path, filename)):
file_path = os.path.join(base_path, filename)
# Get last modified time of file
file_modified_time = os.path.getmtime(file_path)
file_modified_date = datetime.fromtimestamp(file_modified_time).strftime('%Y')
# Create folder for the year if it does not exist
folder_name = file_modified_date
folder_path = os.path.join(base_path, folder_name)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
# Move file to folder
shutil.move(file_path, os.path.join(folder_path, filename))
log.write_log(f"{filename} moved to {folder_name} folder.")
# Function to organize files by extension
def organize_files_by_extension(folder_path):
for filename in os.listdir(folder_path):
if os.path.isfile(os.path.join(folder_path, filename)):
file_path = os.path.join(folder_path, filename)
file_extension = os.path.splitext(filename)[1]
folder_name = file_extension[1:].upper() + " Files"
folder_path_ext = os.path.join(folder_path, folder_name)
# Create folder for the extension if it does not exist
if not os.path.exists(folder_path_ext):
os.makedirs(folder_path_ext)
# Move file to folder
shutil.move(file_path, os.path.join(folder_path_ext, filename))
log.write_log(f"{filename} moved to {folder_name} folder.")
if __name__ == "__main__":
# Get folder path from command line argument
try:
method= sys.argv[1]
folder_path = sys.argv[2]
if method == "date": organize_files_by_date(folder_path)
elif method == "ext": organize_files_by_extension(folder_path)
else: print("Invalid method.")
except IndexError:
print(f"Usage: python {sys.argv[0]} <method> <folder_path>")
exit(1)