Creating a file with python causes `FileNotFoundError`

Viewed 28

I would like to create a new .json file in a different path than the python file is written in. My code is listed below and does not work.

import json

file_name = r'.\Data\Archive-' + str(dt.datetime.now().strftime("%a-%m/%d/%y-%I%p")) + '.json'

file = open(file_name, 'w')

file.dump({})

The error:

FileNotFoundError: [Errno 2] No such file or directory
1 Answers

You most likely got (but you should really include that in your question):

FileNotFoundError: [Errno 2] No such file or directory <your path here>

Your construct the path as a string. Where I live that would currently become:

r'.\Data\Archive-Thu-09/22/22-07AM.json'

The forward and backward slashes are not an issue, Python deals with that nicely, but do you realise that the forward slashes are not allowed in file names, and will be interpreted as path separators?

So, it is trying to write 22-07AM.json to the folder r'.\Data\Archive-Thu-09\22\ - which is probably not what you want.

Try something like this:

import datetime as dt  # uncommon, most people use `from datetime import datetime`

file_name = r'.\Data\Archive-' + str(dt.datetime.now().strftime("%a-%m-%d-%y-%I%p")) + '.json'

If it is what you want, and Python should create those directories automatically, you can:

from pathlib import Path

Path(file_name).parent.mkdir(parents=True)
  • Path(file_name) constructs a Path object from the string
  • .parent takes the parent directory of the file represented by the Path
  • .mkdir() creates that directory, and parents=True ensures needed parent directories are created as well.
Related