原文出处:https://www.cnblogs.com/zhaoyingjie/p/8780383.html
import os import datetime def create_str_to_txt(date,str_data): """ 创建txt,并且写入 """ path_file_name = './action_{}.txt'.format(date) if not os.path.exists(path_file_name): with open(path_file_name, "w") as f: print(f) with open(path_file_name, "a") as f: f.write(str_data) if __name__ == '__main__': create_str_to_txt( datetime.datetime.now().strftime('%Y-%m-%d'),'123')
不追加模式。覆盖写法w+
https://www.runoob.com/python/file-methods.html 参考菜鸟教程python 对file的处理