-
Notifications
You must be signed in to change notification settings - Fork 2
/
filesutilites.py
98 lines (83 loc) · 2.4 KB
/
filesutilites.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
90
91
92
93
94
95
96
97
98
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 21 19:08:53 2014
@author: Slawomir Figiel
Module with the methods working on file paths.
"""
from os.path import isfile, join, isdir, splitext
from os import listdir
def path_reduction(paths):
'''
Method process paths. If in paths is directory, method searches it
for the files. Returns list of files path with paths and files in
directories.
Parameters
==========
paths : enumerate
list of files
Returns
=======
paths : list
list of path files in paths and files in directory in paths
Examples
========
>>> paths = [data/file1.txt, data/file2.pdf, dir/]
>>> path_reduction(paths)
[data/file1.txt, data/file2.pdf, dir/file3.map, dir/file4.rtf]
'''
files = []
for path in paths:
if isdir(path):
files.extend(files_in_dir(path))
else:
files.append(path)
return files
def sort_paths(paths_files, *extensions):
'''
Method sorts paths after file extension and returns a dictionary whose
keys are the extension and the values list of path.
Parameters
==========
paths_files : list paths files
paths to sort
*extensions : strings
extensions that will be included in the dictionary
Returns
=======
sort paths : dict
dictionary whose keys are the extension and values list of
path
Examples
========
>>> paths = ['dir/file1.txt', 'file2.pdf', 'dir/file3.txt',
'file4.rtf', 'file5']
>>> sort_paths(paths, 'txt', 'pdf')
{'txt' : ['dir/file1.txt', 'dir/file3.txt'], 'pdf' : [file2.pdf]}
'''
dict_ext_files = dict((ext, []) for ext in extensions)
dict_keys = dict_ext_files.keys()
for file_ in paths_files:
ext = splitext(file_)[1]
if ext in dict_keys:
dict_ext_files[ext].append(file_)
return dict_ext_files
def files_in_dir(dir_path):
'''
Method return full path files in directory.
Parameters
==========
dir_path : string
directory
Returns
=======
files paths : list
List of full files path in directory.
Examples
========
>>> files_in_dir(dir)
['dir/file1.txt', 'dir/file2', 'dir/file3.pdf']
'''
full = [join(dir_path, f) for f in listdir(dir_path)]
return [f for f in full if isfile(f)]
if __name__ == '__main__':
pass