Reputation: 195
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
Upvotes: 0
Views: 1061
Reputation: 168966
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)
Upvotes: 1