对于需要保存的临时文件进行处理,简单封装了下
import json
import tempfile
import uuid
import os
def save_temp_file(data, mode, suffix):
'''
data: 需要保存的数据
mode: w wb 等
suffix: 文件后缀名,例如 .doc .png
'''
temp_path = tempfile.gettempdir()
uuid_ret = uuid.uuid1()
save_path = os.path.join(temp_path, str(uuid_ret) + suffix)
try:
with open(save_path, mode) as f:
f.write(data)
print(f'文件保存成功,路径为:{save_path}')
except Exception as e:
print(f'文件保存失败,原因{str(e)}')
if __name__ == '__main__':
data = {
"id": 1,
"name": "admin",
}
suffix = '.json'
mode = 'w'
save_temp_file(json.dumps(data), mode, suffix)