簡體   English   中英

在Python中保存json文件時如何定義文件夾名稱?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM