简体   繁体   English

如何从python创建(构造)json文件

[英]how to create(construct) a json file from python

I am attempting to create(not to modify, the file does not exist yet) a json file from python 3.6, and give a specific name, I have read that using open(file, "a"), if the file does not exist, the method will create it. 我正在尝试从python 3.6创建(不修改,该文件尚不存在)一个json文件,并给出一个特定的名称,如果该文件不存在,我已经使用open(file,“ a”)进行了阅读,该方法将创建它。 the method bellow will run ok, but will not create the file, any idea on how to resolve this. 下面的方法可以正常运行,但是不会创建文件,有关如何解决此问题的任何想法。

I have tried the following : 我尝试了以下方法:

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

You don't need the a (append) mode here. 您在这里不需要a (附加)模式。

Also, since it's bad practice to catch exceptions only to print them and continue, I've elided that bit too. 另外,由于仅捕获异常并打印并继续执行是一种不好的做法,因此我也略去了这一点。

Instead, the function will raise an exception if it were about to overwrite an existing file. 相反,如果该函数要覆盖现有文件, 它将引发异常。

Since your date format %Y/%m creates a subdirectory, eg the path will end up being 由于您的日期格式%Y/%m创建了一个子目录,因此路径最终将是

something/2019/04.json 的东西/ 2019 / 04.json

you'll need to make sure the directories inbetween exist. 您需要确保它们之间的目录存在。 os.makedirs does that. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM