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