-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsaving_utils.py
More file actions
51 lines (43 loc) · 1.69 KB
/
Copy pathsaving_utils.py
File metadata and controls
51 lines (43 loc) · 1.69 KB
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
import csv
import json
from pathlib import Path
from typing import Iterable, Union
def replace_extension(path: Union[str, Path], new_ext: str = "") -> Path:
extensions = "".join(Path(path).suffixes)
return Path(str(path).replace(extensions, new_ext))
def append_extension(filename: str, ext: str):
if not '.' in filename:
return filename + f'.{ext}'
if not filename.endswith(ext):
return replace_extension(filename, ext)
return filename
def save_to_csv(content: Iterable[dict], filename):
"""
:param content:
Iterable из словарей, каждый из которых содержит ссылку и контент статьи
:param filename:
Имя файла для записи
:return:
None
"""
filename = append_extension(filename, 'csv')
with open(filename, 'w', newline='', encoding='utf-8') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['Ссылка', 'Тип+Текст'])
for article in content:
value = article.popitem()
link = value[0] # Ссылка
tag_text = value[1] # (формат, текст)
writer.writerow([link, tag_text])
def save_to_json(content: Iterable[dict], filename):
"""
:param content:
Iterable из словарей, каждый из которых содержит ссылку и контент статьи
:param filename:
Имя файла для записи
:return:
None
"""
filename = append_extension(filename, 'json')
with open(filename, 'w', encoding='utf-8') as json_file:
json.dump(content, json_file, ensure_ascii=False, indent=4)