-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfile_utils.py
199 lines (178 loc) · 6.25 KB
/
file_utils.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
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
192
193
194
195
196
197
198
199
"""
File and Folder utils.
"""
import errno
import os
import shutil
import stat
import tarfile
from core.log.log import Log
from core.settings import Settings
class Folder(object):
@staticmethod
def clean(folder):
if Folder.exists(folder=folder):
Log.debug("Clean folder: " + folder)
try:
shutil.rmtree(folder)
except OSError as error:
for root, dirs, files in os.walk(folder, topdown=False):
for name in files:
filename = os.path.join(root, name)
os.chmod(filename, stat.S_IWUSR)
os.remove(filename)
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(folder)
Log.error('Error: %s - %s.' % (error.filename, error.strerror))
@staticmethod
def exists(folder):
return os.path.isdir(folder)
@staticmethod
def is_empty(folder):
return not os.listdir(folder)
@staticmethod
def create(folder):
Log.debug("Create folder: " + folder)
if not os.path.exists(folder):
try:
os.makedirs(folder)
except OSError:
raise
@staticmethod
def copy(source, target, clean_target=True, only_files=False):
"""
Copy folders.
:param source: Source folder.
:param target: Target folder.
:param clean_target: If True clean target folder before copy.
:param only_files: If True only the files from source folder are copied to target folder.
"""
if clean_target:
Folder.clean(folder=target)
Log.info('Copy {0} to {1}'.format(source, target))
if only_files is True:
files = os.listdir(source)
for f in files:
f_path = os.path.join(source, f)
File.copy(f_path, target)
else:
try:
shutil.copytree(source, target)
except OSError as exc:
if exc.errno == errno.ENOTDIR:
shutil.copy(source, target)
else:
raise
@staticmethod
def get_size(folder):
"""
Get folder size in bytes.
:param folder: Folder path.
:return: Size in bytes.
"""
# pylint: disable=unused-variable
total_size = 0
for dirpath, dirnames, filenames in os.walk(folder):
for file_name in filenames:
file_path = os.path.join(dirpath, file_name)
total_size += os.path.getsize(file_path)
return total_size
# noinspection PyUnresolvedReferences
class File(object):
@staticmethod
def read(path):
if File.exists(path):
if Settings.PYTHON_VERSION < 3:
with open(path, 'r') as file_to_read:
output = file_to_read.read()
return str(output.decode('utf8').encode('utf8'))
else:
with open(path, 'r', encoding='utf-8', errors='ignore') as f:
output = f.read()
return output
else:
raise IOError("{0} not found!".format(path))
@staticmethod
def write(path, text):
if Settings.PYTHON_VERSION < 3:
with open(path, 'w+') as text_file:
text_file.write(text)
else:
with open(path, 'w+', encoding='utf-8', errors='ignore') as text_file:
text_file.write(text)
@staticmethod
def append(path, text):
if Settings.PYTHON_VERSION < 3:
with open(path, 'a') as text_file:
text_file.write(text)
else:
with open(path, 'a', encoding='utf-8', errors='ignore') as text_file:
text_file.write(text)
@staticmethod
def replace(path, old_string, new_string):
content = File.read(path=path)
assert old_string in content, 'Can not find "{0}" in {1}'.format(old_string, path)
new_content = content.replace(old_string, new_string)
File.write(path=path, text=new_content)
Log.info("")
Log.info("##### REPLACE FILE CONTENT #####")
Log.info("File: {0}".format(path))
Log.info("Old String: {0}".format(old_string))
Log.info("New String: {0}".format(new_string))
Log.info("")
@staticmethod
def exists(path):
return os.path.isfile(path)
@staticmethod
def copy(src, target):
shutil.copy(src, target)
Log.info('Copy {0} to {1}'.format(os.path.abspath(src), os.path.abspath(target)))
@staticmethod
def delete(path):
if os.path.isfile(path):
os.remove(path)
else:
Log.debug('Error: %s file not found' % path)
@staticmethod
def clean(path):
if os.path.isfile(path):
File.write(path, text='')
else:
raise IOError('Error: %s file not found' % path)
@staticmethod
def find_by_extension(folder, extension):
"""
Find by file extension recursively.
:param folder: Base folder where search is done.
:param extension: File extension.
:return: List of found files.
"""
# pylint: disable=unused-variable
matches = []
if '.' not in extension:
extension = '.' + extension
for root, dirs, files in os.walk(folder):
for f in files:
if f.endswith(extension):
Log.debug('File with {0} extension found: {1}'.format(extension, os.path.abspath(f)))
matches.append(os.path.join(root, f))
return matches
@staticmethod
def extract_part_of_text(text, key_word):
"""
That method will extract text from last occurance of key word
to the end of the file
"""
index = text.rfind(key_word)
text = text[index:]
return text
@staticmethod
def unpack_tar(file_path, dest_dir):
# noinspection PyBroadException
try:
tar_file = tarfile.open(file_path, 'r:gz')
tar_file.extractall(dest_dir)
# pylint: disable=broad-except
except Exception:
Log.debug('Failed to unpack .tar file {0}'.format(file_path))