- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileTree.py
More file actions
Latest commit
191 lines (175 loc) · 7.52 KB
/
Copy pathFileTree.py
File metadata and controls
191 lines (175 loc) · 7.52 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!python
importos
importpathlib
fromrichimportprint
importmimetypes
mimetypes.init()
PIPE="│"
ELBOW="└──"
TEE="├──"
PIPE_PREFIX="│ "
SPACE_PREFIX=" "
classTreeGenerator:
ext=None
def__init__(self, root_dir, file_extension):
self.root_dir=pathlib.Path(root_dir)
self.tree= []
iffile_extension:
self.ext=tuple(
[
extenifexten.startswith(".") else"."+exten
forexteninfile_extension
]
)
# Builder function used to build the entire directory tree
# Main thing to call
defbuild_tree(self):
self.tree_head()
self.tree_body(self.root_dir)
returnself.tree
# Binds the main directory in which the program is called
# This goes at the top of the directory
deftree_head(self):
self.tree.append(f"{self.root_dir}{os.sep}")
self.tree.append(PIPE)
# After the root each directories and their traversal are appended here
# The iterdir function iteratest the present directory giving the list of all items
# in it
deftree_body(self, directory, prefix=""):
entries=directory.iterdir()
# The items so obtained are sorted depending on filetype
# i.e. if the directory has files then they should be listed
# prior to the directories
# The files so obtained are connected via connector
# If its last file end it with elbow else continue with a tee
entries=sorted(entries, key=lambdafentry: fentry.is_file())
entries_count=len(entries)
forindex, entryinenumerate(entries):
try:
connector=ELBOWifindex==entries_count-1elseTEE
# If the type of file is directory then append it using directory type
# connection whilst traversing it again ahead recursively
ifentry.is_dir():
self.add_directory(entry, index, entries_count, prefix, connector)
# Else the type is file so append it using file type connection throughout
else:
self.add_file(entry, prefix, connector)
exceptPermissionError:
continue
defadd_directory(self, directory, index, entries_count, prefix, connector):
# First the name of the directory is appended before traversing
self.tree.append(
f"{prefix}{connector} [bright_yellow]{directory.name}[/]{os.sep}"
)
# if its not last element (file element) then provide a gap in the nesting so formed
# ex if we have dir1, dir2 in fold which is in pfold
# pfold
# │ └──fold
# │<----->├── dir1
# │<----->└── dir2
# Else if its last element then just escape it out with a gap
# ex if we have dir1, dir2 in fold which is in pfold and then next fold in pfold is fold2
# pfold
# │ └──fold
# │ ├── dir1
# │ └── dir2
# │<-----> last element gap
# ├── fold2
ifindex!=entries_count-1:
prefix+=PIPE_PREFIX
else:
prefix+=SPACE_PREFIX
# Recursively traverse everything down the directory
self.tree_body(
directory=directory,
prefix=prefix,
)
self.tree.append(prefix.rstrip())
defadd_file(self, file, prefix, connector):
# Obtain file types just for pretty coloring out different file
# types in different colors
ftype=mimetypes.guess_type(file)[0]
# Check if user specified any file extensions
# helps to locate out specific file types thoughout
# your search directory
ifself.ext:
iffile.name.endswith(self.ext):
ifftypeisnotNone:
matchftype.split("/")[0]:
# If file type is media highlight it with blue
case"image"|"audio"|"video":
self.tree.append(
f"{prefix}{connector} [blue]{file.name}[/]"
)
# If file type is executable highlight it with red
case"application":
self.tree.append(f"{prefix}{connector} [red]{file.name}[/]")
# If file type is source or text highlight it with green
case"text":
self.tree.append(
f"{prefix}{connector} [spring_green3]{file.name}[/]"
)
# If file type is unknown to os then grey it out
else:
self.tree.append(
f"{prefix}{connector} [bright_black]{file.name}[/]"
)
else:
ifftypeisnotNone:
matchftype.split("/")[0]:
# If file type is media highlight it with blue
case"image"|"audio"|"video":
self.tree.append(f"{prefix}{connector} [blue]{file.name}[/]")
# If file type is executable highlight it with red
case"application":
self.tree.append(f"{prefix}{connector} [red]{file.name}[/]")
# If file type is source or text highlight it with green
case"text":
self.tree.append(
f"{prefix}{connector} [spring_green3]{file.name}[/]"
)
# If file type is unknown to os then grey it out
else:
self.tree.append(f"{prefix}{connector} [bright_black]{file.name}[/]")
# Another class more abstraction ¯\(°_o)/¯
classDirectoryTree:
def__init__(self, root_dir, *extension):
self._generator=TreeGenerator(root_dir, extension)
# This generates the tree
defgenerate(self):
tree: list[str] =self._generator.build_tree()
write=input("Want to write it to file (y/n):").lower() =="y"
fname=None
ifwrite:
fname=input(
"Enter full path to file (Leaving empty will create a temp.txt file where this prog executes)\n File Name: "
)
iffnameisnotNoneandos.path.exists(fname) andos.path.isfile(fname):
fpoint=open(fname, "w")
else:
fpoint=open("temp.txt", "w+")
forentryintree:
print(entry, file=fpoint)
print(f"└───[bright_white] Done ────[/]", file=fpoint)
fpoint.close()
else:
forentryintree:
print(entry)
print(f"└───[bright_white] Done ────[/]")
dir_path=input("Enter absolute path to directory: ")
ext=input(
"Enter file extension(s) separated with space. Leave blank to list everything: "
)
ifext!="":
ext=ext.split(" ")
else:
ext=None
ifos.path.exists(dir_path) andos.path.isdir(dir_path):
ifextisnotNone:
f_tree=DirectoryTree(dir_path, *ext)
f_tree.generate()
else:
f_tree=DirectoryTree(dir_path)
f_tree.generate()
else:
print("Entered directory doesn't exists")