在保存文件前,先判断保存路径是否已存在,如果不存在则创建对应的目录。
代码示例:
import os
file_path = 'path/to/file.txt' if not os.path.isdir(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path))
with open(file_path, 'w') as f: f.write('content')
上一篇:保存csv字符文件时丢失数据
下一篇:保存带插值和alpha通道的imshow图像为pdf时出现Matplotlib问题。