代码
import os
def save_data_to_file(html, file_path, mode='w', encoding='utf-8'):
'''
保存字符串到指定文件
Args:
html: str 字符串数据
file_path: str 文件路径
mode: str 文件打开格式,[w,r,a...]
encoding: str 文件编码格式 [utf-8, gbk]
Returns: list True/False, message
'''
file_path_dir = os.path.dirname(file_path)
if not os.path.exists(file_path_dir):
os.makedirs(file_path_dir)
try:
with open(file_path, mode, encoding=encoding) as f:
f.write(html)
return True, '保存成功'
except Exception as e:
return False, '保存失败:{}'.format(e)
if __name__ == "__main__":
html = '字符串数据'
file_path = 'D:/a/b/1.txt'
save(html, file_path, encoding='gbk')