-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathutils.py
53 lines (47 loc) · 1.88 KB
/
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
# utils.py
# -*- coding: utf-8 -*-
import os
import json
def read_file(filename: str) -> str:
"""读取文件的全部内容,若文件不存在或异常则返回空字符串。"""
try:
with open(filename, 'r', encoding='utf-8') as file:
content = file.read()
return content
except FileNotFoundError:
return ""
except Exception as e:
print(f"[read_file] 读取文件时发生错误: {e}")
return ""
def append_text_to_file(text_to_append: str, file_path: str):
"""在文件末尾追加文本(带换行)。若文本非空且无换行,则自动加换行。"""
if text_to_append and not text_to_append.startswith('\n'):
text_to_append = '\n' + text_to_append
try:
with open(file_path, 'a', encoding='utf-8') as file:
file.write(text_to_append)
except IOError as e:
print(f"[append_text_to_file] 发生错误:{e}")
def clear_file_content(filename: str):
"""清空指定文件内容。"""
try:
with open(filename, 'w', encoding='utf-8') as file:
pass
except IOError as e:
print(f"[clear_file_content] 无法清空文件 '{filename}' 的内容:{e}")
def save_string_to_txt(content: str, filename: str):
"""将字符串保存为 txt 文件(覆盖写)。"""
try:
with open(filename, 'w', encoding='utf-8') as file:
file.write(content)
except Exception as e:
print(f"[save_string_to_txt] 保存文件时发生错误: {e}")
def save_data_to_json(data: dict, file_path: str) -> bool:
"""将数据保存到 JSON 文件。"""
try:
with open(file_path, 'w', encoding='utf-8') as json_file:
json.dump(data, json_file, ensure_ascii=False, indent=4)
return True
except Exception as e:
print(f"[save_data_to_json] 保存数据到JSON文件时出错: {e}")
return False