![](/img/trans.png)
[英]Saving file with a name containing / at the destination folder in python
[英]How to define folder name when saving json file in Python?
保存 JSON 文件時如何定義文件夾名稱? 我試圖在open()
中添加myfoldername
,但沒有奏效。 還嘗試在文件名定義中使用myfoldername/myfilename
錯誤:
TypeError: an integer is required (got type str)
代碼:
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()
這應該可以解決問題。
pathlib
管理路徑mkdir
創建父目錄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.