-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataBaze.py
225 lines (185 loc) · 9.94 KB
/
DataBaze.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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
import os, json, shutil
from datetime import datetime
class DataFile:
"""
DataFile(name, type, encode, path, logs)
name - Название файла
type - Расширение файла (default - json)
encode - Кодировка файла (default - utf-8)
path - Путь до файла (default - .)
logs - Показывать/Скрывать логи (default - False)
.create() - создает файл и, при необходимости, создает папку
.read() - чтение файла (если файл - json, то автоматическое переобразование в словарь)
.write(data) - запись данных в файл (если файл - json, то автоматическое переобразование в строчку)
.delete() - удаление файла
.rename(new_name) - переименование файла
.info() - возвращает информацию о файле (родительская папка, путь, размер, название, дата последнего изменения)
"""
def __init__(self, name: str, type: str = "json", encode: str = "utf-8", path: str = ".", logs: bool = False):
"""
name - Название файла
type - Расширение файла (default - json)
encode - Кодировка файла (default - utf-8)
path - Путь до файла (default - .)
logs - Показывать/Скрывать логи (default - False)
"""
self.name = name
self.type = type
self.encode = encode
self.path = path
self.logs = logs
def create(self):
"""
.create() - создает файл и, при необходимости, создает папку
"""
file_path = os.path.join(self.path, f'{self.name}.{self.type}')
if not os.path.exists(self.path):
os.makedirs(self.path)
if not os.path.exists(file_path):
try:
with open(file_path, 'w', encoding=self.encode) as f:
f.write("")
if self.logs: print(f'[DataFile - Create] {file_path} успешно создан.')
except Exception as e:
if self.logs: print(f'[DataFile - Create] Ошибка при создании файла {file_path}: {e}')
else:
if self.logs: print(f'[DataFile - Create] Файл уже существует: {file_path}')
def read(self):
"""
.read() - чтение файла (если файл - json, то автоматическое преобразование в словарь)
"""
file_path = os.path.join(self.path, f'{self.name}.{self.type}')
if os.path.exists(file_path):
try:
with open(file_path, "r", encoding=self.encode) as f:
if self.type == "json":
content = f.read()
if content.strip():
return json.loads(content)
else:
return {}
else:
return f.read()
if self.logs: print(f'[DataFile - Read] Файл {file_path} успешно прочтен.')
except json.JSONDecodeError as e:
if self.logs: print(f'[DataFile - Read] Ошибка при чтении файла {file_path}: {e}')
except Exception as e:
if self.logs: print(f'[DataFile - Read] Неизвестная ошибка при чтении файла {file_path}: {e}')
else:
if self.logs: print(f'[DataFile - Read] Файл {file_path} не найден.')
return None
def write(self, data, rewrite: bool = True):
"""
.write(data, type) - запись данных в файл (если файл - json, то автоматическое переобразование в строчку)
data - Данные
rewrite - Перезаписывать (True/False)
"""
file_path = os.path.join(self.path, f'{self.name}.{self.type}')
if os.path.exists(file_path):
try:
if not rewrite:
with open(file_path, "a", encoding=self.encode) as f:
if self.type == "json":
f.write(json.dumps(data, ensure_ascii=False, indent=4))
if self.logs: print(f'[DataFile - Write] Данные успешно записаны в файл {file_path}')
else:
f.write(str(data))
if self.logs: print(f'[DataFile - Write] Данные успешно записаны в файл {file_path}')
else:
with open(file_path, "w", encoding=self.encode) as f:
if self.type == "json":
f.write(json.dumps(data, ensure_ascii=False, indent=4))
if self.logs: print(f'[DataFile - Write] Данные успешно записаны в файл {file_path}')
else:
f.write(str(data))
if self.logs: print(f'[DataFile - Write] Данные успешно записаны в файл {file_path}')
except TypeError as e:
if self.logs: print(f'[DataFile - Write] Ошибка при записи в файл {file_path}: {e}')
except Exception as e:
if self.logs: print(f'[DataFile - Write] Неизвестная ошибка при записи в файл {file_path}: {e}')
else:
if self.logs: print(f'[DataFile - Write] Файл {file_path} не найден.')
def delete(self):
"""
.delete() - удаление файла
"""
file_path = os.path.join(self.path, f'{self.name}.{self.type}') if self.type != "" else ""
if os.path.exists(file_path):
try:
if os.path.isfile(file_path):
os.remove(file_path)
if self.logs: print(f"[DataFile - Delete] Файл {file_path} успешно удален.")
except Exception as e:
if self.logs: print(f"[DataFile - Delete] Ошибка при удалении файла {file_path}: {e}")
else:
if self.logs: print(f'[DataFile - Delete] Файл {file_path} не найден.')
def rename(self, new_name: str):
"""
.rename(new_name) - переименование файла
"""
old_file_path = os.path.join(self.path, f'{self.name}.{self.type}')
new_file_path = os.path.join(self.path, f'{new_name}.{self.type}')
if os.path.exists(old_file_path):
os.rename(old_file_path, new_file_path)
if self.logs: print(f"[DataFile - Rename] Файл {self.name} успешно переименнован в {new_name}")
self.name = new_name
else:
if self.logs: print(f'[DataFile - Rename] Файл {old_file_path} не найден.')
def info(self):
"""
.info() - возвращает информацию о файле (родительская папка, путь, размер, название, дата последнего изменения)
"""
file_path = os.path.join(self.path, f'{self.name}.{self.type}')
if os.path.exists(file_path):
file_info = os.stat(file_path)
parent_folder = os.path.dirname(file_path)
file_size = file_info.st_size
last_modified = file_info.st_mtime
last_modified_formatted = datetime.fromtimestamp(last_modified).strftime('%d.%m.%Y %H:%M:%S')
info = {
"name": f'{self.name}.{self.type}',
"path": file_path,
"father": parent_folder,
"size": file_size,
"modified": last_modified_formatted,
}
if self.logs: print(f"[DataFile - Info] Информация о файле {file_path} успешно получена.")
return info
else:
if self.logs: print(f'[DataFile - Info] Файл {file_path} не найден.')
return None
class DataBaze:
"""
DataBaze(path, logs)
path - путь до папки
logs - Показывать/Скрывать логи (default - False)
.file(name, type, encode) - обьявляет файл
.delete() - удаляет все файлы в базе данных
"""
def __init__(self, path: str = "data/", logs: bool = False):
"""
path - путь до папки
logs - Показывать/Скрывать логи (default - False)
"""
self.path = path
self.logs = logs
def file(self, name: str, type: str = "json", encode: str = "utf-8"):
"""
.file(name, type, encode) - обьявляет файл
"""
return DataFile(name, type, encode, self.path, self.logs)
def delete(self):
"""
.delete() - удаляет все файлы в папке
"""
if os.path.exists(self.path):
try:
shutil.rmtree(self.path)
if self.logs:
print(f"[DataFile - Delete] Папка {self.path} успешно удалена.")
except Exception as e:
if self.logs:
print(f"[DataFile - Delete] Ошибка при удалении папки {self.path}: {e}")
else:
if self.logs:
print(f'[DataFile - Delete] Папка {self.path} не найдена.')