简体   繁体   中英

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. 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.

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

something/2019/04.json

you'll need to make sure the directories inbetween exist. os.makedirs does that.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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