-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutilities.py
154 lines (136 loc) · 5.17 KB
/
utilities.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
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
import os
import sys
from hashlib import md5
import math
import configparser
import shutil
config = configparser.ConfigParser()
config_file = os.path.join(os.path.dirname(__file__), 'settings.cfg')
config.read(config_file)
cfg_path = config['Server']['path']
cfg_limit = int(config['Server']['limit'])
class filesandfolders:
def deletefiles(dir):
if os.path.exists(dir):
filelist = [f for f in os.listdir(dir)]
for f in filelist:
byebye = os.path.join(dir, f)
if os.path.isfile(byebye):
os.remove(byebye)
else:
print('ERROR: {d} is not a local path'.format(d=byebye))
def deletefolder(dir):
if os.path.exists(dir):
os.rmdir(dir)
else:
print('ERROR: {d} is not a local path'.format(d=dir))
def freespace(d):
foldersize = int(math.floor(filesandfolders.getFolderSize(d) / 1024**3))
if foldersize > (cfg_limit - 1): # -1 to be sure to be under the limit
r = 0
else:
r = 1
return r
def getFolderSize(d):
total_size = 0
for dirpath, dirnames, filenames in os.walk(d):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
def getFileSize(d):
try:
b = os.path.getsize(d)
return b
except:
return 0
# def getFileNamesFromFolder(d):
# fn = []
# for dirpath, dirnames, filenames in os.walk(d):
# for f in filenames:
# fn = fn + [f]
# return fn
def md5sum(filename):
""" https://bitbucket.org/prologic/tools/src/tip/md5sum?fileviewer=file-view-default """
hash = md5()
with open(filename, "rb") as f:
for chunk in iter(lambda: f.read(128 * hash.block_size), b""):
hash.update(chunk)
return hash.hexdigest()
def listdirs(folder):
""" https://stackoverflow.com/a/142368/1623867 """
return [d for d in os.listdir(folder) if os.path.isdir(os.path.join(folder, d))]
def copyDirAndFiles(root_src_dir, root_dst_dir):
""" https://stackoverflow.com/a/7420617/1623867 """
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
counter = 0
for file_ in files:
counter += 1
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
print('INFO: Copy file {c: >3}/{ttl} {s} to {d}'.format(
c=counter,
ttl=len(files),
s=file_,
d=dst_dir
))
shutil.copy(src_file, dst_dir)
def moveDirAndFiles(root_src_dir, root_dst_dir):
""" https://stackoverflow.com/a/7420617/1623867 """
for src_dir, dirs, files in os.walk(root_src_dir):
dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
counter = 0
for file_ in files:
counter += 1
src_file = os.path.join(src_dir, file_)
dst_file = os.path.join(dst_dir, file_)
if os.path.exists(dst_file):
os.remove(dst_file)
print('INFO: Move file {c: >3}/{ttl} {s} to {d}'.format(
c=counter,
ttl=len(files),
s=file_,
d=dst_dir
))
shutil.move(src_file, dst_dir)
class queries:
def query_yes_no(question, default='yes'):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is one of "yes" or "no".
"""
# from http://code.activestate.com/recipes/577058-query-yesno/
valid = {
'yes': 'yes',
'y': 'yes',
'ye': 'yes',
'no': 'no',
'n': 'no'
}
if default is None:
prompt = ' [y/n] '
elif default == 'yes':
prompt = ' [Y/n] '
elif default == 'no':
prompt = ' [y/N] '
else:
raise ValueError('invalid default answer: {d}'.format(d=default))
while 1:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return default
elif choice in valid.keys():
return valid[choice]
else:
sys.stdout.write('Please respond with \'yes\' or \'no\' (or \'y\' or \'n\').')