filecreator 0.1.0__tar.gz

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.
@@ -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.
@@ -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,11 @@
1
+ # filecreator
2
+
3
+ 📄 Удобная библиотека на Python для создания файлов разных форматов.
4
+ Функция `createfile()` сама определяет формат по расширению файла.
5
+
6
+ **Автор:** Богдан Полтавский (bogpolt@gmail.com)
7
+
8
+ ## Установка
9
+
10
+ ```bash
11
+ pip install filecreator
@@ -0,0 +1,4 @@
1
+ from .createfile import createfile, readfile, deletefile
2
+
3
+ __version__ = "0.1.0"
4
+ __all__ = ["createfile", "readfile", "deletefile"]
@@ -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
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "filecreator"
7
+ version = "0.1.0"
8
+ authors = [
9
+ { name = "Богдан Полтавский", email = "bogpolt@gmail.com" },
10
+ ]
11
+ description = "Удобная библиотека для создания файлов разных форматов"
12
+ readme = "README.md"
13
+ requires-python = ">=3.7"
14
+ license = { text = "MIT" }
15
+ keywords = ["file", "create", "json", "csv", "txt", "utility"]
16
+ classifiers = [
17
+ "Development Status :: 3 - Alpha",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Operating System :: OS Independent",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.7",
23
+ "Programming Language :: Python :: 3.8",
24
+ "Programming Language :: Python :: 3.9",
25
+ "Programming Language :: Python :: 3.10",
26
+ "Programming Language :: Python :: 3.11",
27
+ "Programming Language :: Python :: 3.12",
28
+ "Topic :: Software Development :: Libraries :: Python Modules",
29
+ "Topic :: Utilities",
30
+ ]
31
+
32
+ [project.urls]
33
+ Homepage = "https://github.com/bogpolt/filecreator"
34
+ Repository = "https://github.com/bogpolt/filecreator"
35
+ Issues = "https://github.com/bogpolt/filecreator/issues"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["filecreator"]
@@ -0,0 +1,91 @@
1
+ """
2
+ Простой ручной тест библиотеки filecreator.
3
+ Запуск: python example.py
4
+ """
5
+
6
+ from filecreator import createfile, readfile, deletefile
7
+ from pathlib import Path
8
+
9
+
10
+ def main():
11
+ print("=" * 50)
12
+ print("🧪 Тест библиотеки filecreator")
13
+ print("=" * 50)
14
+
15
+ # --- 1. Текстовый файл ---
16
+ print("\n1️⃣ Создаём текстовый файл...")
17
+ p = createfile(name="test_output/hello.txt", content="Привет, мир!")
18
+ print(f" ✅ Создан: {p}")
19
+ print(f" 📖 Прочитан: {readfile(p)}")
20
+
21
+ # --- 2. JSON ---
22
+ print("\n2️⃣ Создаём JSON...")
23
+ data = {"name": "Богдан", "age": 25, "skills": ["Python", "SQL"]}
24
+ p = createfile(name="test_output/user.json", content=data)
25
+ print(f" ✅ Создан: {p}")
26
+ print(f" 📖 Прочитан: {readfile(p)}")
27
+
28
+ # --- 3. CSV из списка списков ---
29
+ print("\n3️⃣ Создаём CSV (список списков)...")
30
+ p = createfile(
31
+ name="test_output/report.csv",
32
+ content=[[1, "Яблоко", 100], [2, "Груша", 150]],
33
+ headers=["id", "название", "цена"],
34
+ )
35
+ print(f" ✅ Создан: {p}")
36
+ print(f" 📖 Прочитан: {readfile(p)}")
37
+
38
+ # --- 4. CSV из списка словарей ---
39
+ print("\n4️⃣ Создаём CSV (список словарей)...")
40
+ p = createfile(
41
+ name="test_output/users.csv",
42
+ content=[
43
+ {"id": 1, "name": "Иван", "city": "Москва"},
44
+ {"id": 2, "name": "Мария", "city": "Питер"},
45
+ ],
46
+ )
47
+ print(f" ✅ Создан: {p}")
48
+ print(f" 📖 Прочитан: {readfile(p)}")
49
+
50
+ # --- 5. Markdown ---
51
+ print("\n5️⃣ Создаём Markdown...")
52
+ p = createfile(name="test_output/readme.md", content="# Заголовок\n\nТекст.")
53
+ print(f" ✅ Создан: {p}")
54
+
55
+ # --- 6. Бинарный файл ---
56
+ print("\n6️⃣ Создаём бинарный файл...")
57
+ p = createfile(name="test_output/blob.bin", content=b"\x00\x01\x02\x03")
58
+ print(f" ✅ Создан: {p}")
59
+ print(f" 📖 Прочитан: {readfile(p)}")
60
+
61
+ # --- 7. Дозапись ---
62
+ print("\n7️⃣ Тестируем дозапись...")
63
+ createfile(name="test_output/log.txt", content="Строка 1\n")
64
+ createfile(name="test_output/log.txt", content="Строка 2\n", append=True)
65
+ print(f" 📖 Содержимое: {readfile('test_output/log.txt')!r}")
66
+
67
+ # --- 8. Автосоздание вложенных папок ---
68
+ print("\n8️⃣ Тестируем создание вложенных папок...")
69
+ p = createfile(name="test_output/a/b/c/deep.txt", content="Глубоко!")
70
+ print(f" ✅ Создан: {p}")
71
+
72
+ # --- 9. Ошибка при overwrite=False ---
73
+ print("\n9️⃣ Тестируем overwrite=False...")
74
+ try:
75
+ createfile(name="test_output/hello.txt", content="x", overwrite=False)
76
+ print(" ❌ Ошибка: должно было выбросить FileExistsError")
77
+ except FileExistsError as e:
78
+ print(f" ✅ Поймали ошибку: {e}")
79
+
80
+ # --- 10. Удаление ---
81
+ print("\n🔟 Тестируем удаление...")
82
+ ok = deletefile("test_output/hello.txt")
83
+ print(f" ✅ Удалено: {ok}, файл существует: {Path('test_output/hello.txt').exists()}")
84
+
85
+ print("\n" + "=" * 50)
86
+ print("✅ Все тесты пройдены!")
87
+ print("=" * 50)
88
+
89
+
90
+ if __name__ == "__main__":
91
+ main()