0

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
4
  • a mode is for appending. How can you append to a file that doesn't exist? Thus, this mode does not create the file. You want w mode. Commented Apr 8, 2019 at 16:34
  • What operating system? That should create the file; you just never wrote any data to it. Commented Apr 8, 2019 at 16:35
  • Possible duplicate of How to build JSON from python script? Commented Apr 8, 2019 at 16:35
  • you can also do a+ as this will to create a new file @kindall Commented Apr 8, 2019 at 16:35

1 Answer 1

1

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, e.g. 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)

Sign up to request clarification or add additional context in comments.

2 Comments

this definitely works, @AKX what can I change to leave the file in the same directory ?
Change your "monthly_name" pattern to something that doesn't have a slash, e.g. %Y-%m.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.