0

I want to save JSON-data to a (before not existing) file using the following code, which works with Python 3.6.5:

with open("Samples\\{}.json".format(id), "w", encoding="utf-8") as f:
    json.dump(labels, f, ensure_ascii=False, indent=4)

This will create a new .json file in the folder Samples.
Now I tried the same with Python 3.7.3, but instead of creating a new .json file in said directory, it creates a file with a name like "Samples\xyz.json" in the directory the python code is running (running in a jupyter notebook).

I tried the following already, but it results in the same problem creating a file with the directory as file name:

f = open(os.path.expanduser(os.path.join("Samples/{}.json".format(document_id)))
json.dump(labels, f, ensure_ascii=False, indent=4)

How can I create a new .json file in the desired directory with Python 3.7.3?

2
  • 1
    you are using join incorrectly.. it should be join('Examples', '{}.json'.format(doc)) Commented Apr 23, 2020 at 11:33
  • @johnashu I get an error "[Errno 2] No such file or directory" since the .json doesn't exist before Commented Apr 23, 2020 at 11:41

1 Answer 1

3

with pathlib & f-string:

from pathlib import Path
document_id = 100 # Random id here ...
sample_file = Path("Samples") / f"{document_id}.json"
sample_file.parent.mkdir(exist_ok=True)
with sample_file.open("w", encoding="utf-8") as f:
    json.dump(labels, f, ensure_ascii=False, indent=4)
Sign up to request clarification or add additional context in comments.

Comments

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.