[英]how to create(construct) a json file from python
我正在嘗試從python 3.6創建(不修改,該文件尚不存在)一個json文件,並給出一個特定的名稱,如果該文件不存在,我已經使用open(file,“ a”)進行了閱讀,該方法將創建它。 下面的方法可以正常運行,但是不會創建文件,有關如何解決此問題的任何想法。
我嘗試了以下方法:
def create_file(self):
import os
monthly_name = datetime.now().strftime('%m/%Y')
file=monthly_name + ".json"
file_path = os.path.join(os.getcwd(), file)
if not os.path.exists(file_path) or new_file:
print("Creating file...")
try:
open(file, "a")
except Exception as e:
print (e)
else:
pass
您在這里不需要a
(附加)模式。
另外,由於僅捕獲異常並打印並繼續執行是一種不好的做法,因此我也略去了這一點。
相反,如果該函數將要覆蓋現有文件, 它將引發異常。
由於您的日期格式%Y/%m
創建了一個子目錄,因此路徑最終將是
的東西/ 2019 / 04.json
您需要確保它們之間的目錄存在。 os.makedirs
做到了。
import os
import json
# ...
def create_file(self):
monthly_name = datetime.now().strftime("%Y/%m")
file_path = monthly_name + ".json"
file_dir = os.path.dirname(file_path) # Get the directory name from the full filepath
os.makedirs(file_dir, exist_ok=True)
if os.path.exists(file_path):
raise RuntimeError("file exists, not overwriting")
with open(file_path, "w") as fp:
json.dump({"my": "data"}, fp)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.