filecreator 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
filecreator/__init__.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Универсальный создатель файлов.
|
|
3
|
+
Функция createfile() сама определяет формат по расширению файла.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import csv
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
__all__ = ["createfile", "readfile", "deletefile"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def createfile(
|
|
14
|
+
name: str,
|
|
15
|
+
content=None,
|
|
16
|
+
encoding: str = "utf-8",
|
|
17
|
+
append: bool = False,
|
|
18
|
+
indent: int = 4,
|
|
19
|
+
delimiter: str = ",",
|
|
20
|
+
headers: list = None,
|
|
21
|
+
ensure_ascii: bool = False,
|
|
22
|
+
overwrite: bool = True,
|
|
23
|
+
**kwargs
|
|
24
|
+
):
|
|
25
|
+
"""
|
|
26
|
+
Создаёт файл с автоматическим определением формата по расширению.
|
|
27
|
+
|
|
28
|
+
Параметры:
|
|
29
|
+
----------
|
|
30
|
+
name : str
|
|
31
|
+
Путь к файлу (например: "data/info.json").
|
|
32
|
+
content : any
|
|
33
|
+
Содержимое файла:
|
|
34
|
+
- str → для .txt, .md, .html, .py и т.д.
|
|
35
|
+
- dict/list → для .json
|
|
36
|
+
- list[list] / list[dict] → для .csv
|
|
37
|
+
- bytes → для бинарных файлов (.bin, .png и т.д.)
|
|
38
|
+
encoding : str
|
|
39
|
+
Кодировка для текстовых файлов.
|
|
40
|
+
append : bool
|
|
41
|
+
Дописать в конец, а не перезаписывать (для текстовых).
|
|
42
|
+
indent : int
|
|
43
|
+
Отступ для JSON.
|
|
44
|
+
delimiter : str
|
|
45
|
+
Разделитель для CSV.
|
|
46
|
+
headers : list
|
|
47
|
+
Заголовки для CSV (если content — список списков).
|
|
48
|
+
ensure_ascii : bool
|
|
49
|
+
Для JSON: экранировать ли не-ASCII символы.
|
|
50
|
+
overwrite : bool
|
|
51
|
+
Если False и файл существует — выбросит ошибку.
|
|
52
|
+
|
|
53
|
+
Возвращает:
|
|
54
|
+
-----------
|
|
55
|
+
Path — путь к созданному файлу.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
path = Path(name)
|
|
59
|
+
|
|
60
|
+
# Проверка на перезапись
|
|
61
|
+
if path.exists() and not overwrite and not append:
|
|
62
|
+
raise FileExistsError(f"Файл уже существует: {path}")
|
|
63
|
+
|
|
64
|
+
# Создаём родительские папки
|
|
65
|
+
if path.parent and not path.parent.exists():
|
|
66
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
|
|
68
|
+
ext = path.suffix.lower()
|
|
69
|
+
|
|
70
|
+
# === JSON ===
|
|
71
|
+
if ext == ".json":
|
|
72
|
+
if content is None:
|
|
73
|
+
content = {}
|
|
74
|
+
with open(path, "w", encoding=encoding) as f:
|
|
75
|
+
json.dump(content, f, indent=indent, ensure_ascii=ensure_ascii)
|
|
76
|
+
return path
|
|
77
|
+
|
|
78
|
+
# === CSV ===
|
|
79
|
+
if ext == ".csv":
|
|
80
|
+
mode = "a" if append else "w"
|
|
81
|
+
with open(path, mode, encoding=encoding, newline="") as f:
|
|
82
|
+
writer = csv.writer(f, delimiter=delimiter)
|
|
83
|
+
|
|
84
|
+
# Если это список словарей
|
|
85
|
+
if content and isinstance(content, list) and isinstance(content[0], dict):
|
|
86
|
+
fieldnames = headers or list(content[0].keys())
|
|
87
|
+
dict_writer = csv.DictWriter(f, fieldnames=fieldnames, delimiter=delimiter)
|
|
88
|
+
if not append:
|
|
89
|
+
dict_writer.writeheader()
|
|
90
|
+
dict_writer.writerows(content)
|
|
91
|
+
else:
|
|
92
|
+
if headers and not append:
|
|
93
|
+
writer.writerow(headers)
|
|
94
|
+
if content:
|
|
95
|
+
writer.writerows(content)
|
|
96
|
+
return path
|
|
97
|
+
|
|
98
|
+
# === Бинарные файлы ===
|
|
99
|
+
if isinstance(content, (bytes, bytearray)):
|
|
100
|
+
with open(path, "wb") as f:
|
|
101
|
+
f.write(content)
|
|
102
|
+
return path
|
|
103
|
+
|
|
104
|
+
# === Текстовые (txt, md, html, py, log и т.д.) ===
|
|
105
|
+
mode = "a" if append else "w"
|
|
106
|
+
text = "" if content is None else str(content)
|
|
107
|
+
with open(path, mode, encoding=encoding) as f:
|
|
108
|
+
f.write(text)
|
|
109
|
+
return path
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def readfile(name: str, encoding: str = "utf-8"):
|
|
113
|
+
"""Читает файл, определяя формат по расширению."""
|
|
114
|
+
path = Path(name)
|
|
115
|
+
if not path.exists():
|
|
116
|
+
raise FileNotFoundError(f"Файл не найден: {path}")
|
|
117
|
+
|
|
118
|
+
ext = path.suffix.lower()
|
|
119
|
+
|
|
120
|
+
if ext == ".json":
|
|
121
|
+
with open(path, "r", encoding=encoding) as f:
|
|
122
|
+
return json.load(f)
|
|
123
|
+
|
|
124
|
+
if ext == ".csv":
|
|
125
|
+
with open(path, "r", encoding=encoding, newline="") as f:
|
|
126
|
+
return list(csv.reader(f))
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
with open(path, "r", encoding=encoding) as f:
|
|
130
|
+
return f.read()
|
|
131
|
+
except UnicodeDecodeError:
|
|
132
|
+
with open(path, "rb") as f:
|
|
133
|
+
return f.read()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def deletefile(name: str) -> bool:
|
|
137
|
+
"""Удаляет файл. Возвращает True, если удалил."""
|
|
138
|
+
path = Path(name)
|
|
139
|
+
if path.exists():
|
|
140
|
+
path.unlink()
|
|
141
|
+
return True
|
|
142
|
+
return False
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: filecreator
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Удобная библиотека для создания файлов разных форматов
|
|
5
|
+
Project-URL: Homepage, https://github.com/bogpolt/filecreator
|
|
6
|
+
Project-URL: Repository, https://github.com/bogpolt/filecreator
|
|
7
|
+
Project-URL: Issues, https://github.com/bogpolt/filecreator/issues
|
|
8
|
+
Author-email: Богдан Полтавский <bogpolt@gmail.com>
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: create,csv,file,json,txt,utility
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
24
|
+
Classifier: Topic :: Utilities
|
|
25
|
+
Requires-Python: >=3.7
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
# filecreator
|
|
29
|
+
|
|
30
|
+
📄 Удобная библиотека на Python для создания файлов разных форматов.
|
|
31
|
+
Функция `createfile()` сама определяет формат по расширению файла.
|
|
32
|
+
|
|
33
|
+
**Автор:** Богдан Полтавский (bogpolt@gmail.com)
|
|
34
|
+
|
|
35
|
+
## Установка
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install filecreator
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
filecreator/__init__.py,sha256=SSusK8cQ5uymLuhv-QRMc13an76sqOHnIEM77jKbiCc,133
|
|
2
|
+
filecreator/createfile.py,sha256=ffpMU1aBCSsRs3yGBDjMHBJfaWjpXdVn6FxECaLqJuQ,4819
|
|
3
|
+
filecreator-0.1.0.dist-info/METADATA,sha256=krZPKihagH1-qvtYL01n-K8wx3VYmns7DaCw02ORnfY,1584
|
|
4
|
+
filecreator-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
|
|
5
|
+
filecreator-0.1.0.dist-info/licenses/LICENSE,sha256=tzYrZ02p-YXP-h-LoabrkXuF29p5yjeVSDcfE6zD8c8,1109
|
|
6
|
+
filecreator-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Богдан Полтавский
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|