-
Notifications
You must be signed in to change notification settings - Fork 2
/
organizer.py
executable file
·89 lines (73 loc) · 2.52 KB
/
organizer.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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "nagracks"
__date__ = "14-07-2016"
__license__ = "MIT"
__copyright__ = "Copyright © 2016 nagracks"
import argparse
import collections
import os
import shutil
class Organizer(object):
"""Organizer"""
def __init__(self, path):
self.path = path
self.home_dir = os.path.expanduser('~')
def filetype_dict(self):
"""Make dictionary of {[key=file-extension]:[value=files..]}
:returns: dictionary, default dictionary class
"""
# Make defaultdict #
filetypes = collections.defaultdict(list)
# Iterate over path #
for ele in os.listdir(self.path):
if os.path.isfile(os.path.join(self.path, ele)):
# Get file-extension without dot #
file_ext = os.path.splitext(ele)[-1].split('.')[-1]
# Make dictionary pairs #
filetypes[file_ext].append(ele)
return filetypes
def make_dirs(self):
"""Make require directories if they don't exist
:returns: None
"""
# Iterate on dictionary keys #
# Make directories of present keys #
# With condition, if dirs exists then pass on #
# Else make directories #
# path is /home/user/Organizer/keys.. #
for dir_name in self.filetype_dict().keys():
dir_path = os.path.join(self.home_dir, 'Organizer', dir_name)
if os.path.exists(dir_path):
pass
else:
os.mkdir(dir_path)
def organize_files(self):
"""Organize/move all files to corresponding directories
:returns: None
"""
for k, v in self.filetype_dict().items():
# Iterate over dictionary value #
for files in v:
# Make source and destination paths #
src_path = os.path.join(self.path, files)
dst_path = os.path.join(self.home_dir, 'Organizer', k)
# Move them #
shutil.move(src_path, dst_path)
if __name__ == "__main__":
# Commandline args
parser = argparse.ArgumentParser(
description="Organizer"
)
parser.add_argument(
'-d',
'--directory',
dest='directory',
metavar='/full/directory/path',
action='store',
help="directory you want to organize"
)
args = parser.parse_args()
org = Organizer(args.directory)
org.make_dirs()
org.organize_files()