[英]How to define folder name when saving json file in Python?
How to define folder name when saving JSON file?保存 JSON 文件时如何定义文件夹名称? I tried to add myfoldername
inside open()
, but did not work.我试图在open()
中添加myfoldername
,但没有奏效。 Also tried to myfoldername/myfilename
in filename definition还尝试在文件名定义中使用myfoldername/myfilename
Error:错误:
TypeError: an integer is required (got type str)
Code:代码:
import json
# Testing file save
dictionary_data = {"a": 1, "b": 2}
filename = "myfilename" + time.strftime("%Y%m%d-%H%M%S") + ".json"
a_file = open("myfoldername",filename, "w")
json.dump(dictionary_data, a_file)
a_file.close()
This should do the trick.这应该可以解决问题。
pathlib
to manage paths使用pathlib
管理路径mkdir
如果不存在,则使用mkdir
创建父目录with
statement通过with
语句打开文件import json
import time
from pathlib import Path
# Testing file save
dictionary_data = {"a": 1, "b": 2}
filename = Path("myfilename") / Path(f"{time.strftime('%Y%m%d-%H%M%S')}.json")
# create the parent dir if not exist
filename.parent.mkdir(parents=True, exist_ok=True)
with open(filename, "w") as a_file:
json.dump(dictionary_data, a_file)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.