Essex
Essex

Reputation: 6138

Django : Create a dynamic path with BASE_DIR

I have a very simple question but I don't understand why it doesn't work. I would like to set the path to .json file like this :

with open(settings.BASE_DIR + '../../package.json') as package_json_file:

But i'm getting this issue :

FileNotFoundError: [Errno 2] No such file or directory: '/home/val/Bureau/Projets/APP/app/src../../package.json'

How I can define the path from BASE_DIR and come back to .json file ?

Upvotes: 1

Views: 490

Answers (2)

Serafeim
Serafeim

Reputation: 15104

First of all the problem in your code should be obvious: You are missing backslash between the BASE_DIR and the hard coded path you are adding. This this

with open(settings.BASE_DIR + '/../../package.json') as package_json_file:

should work (if the package is there of course).

However, to avoid such inconsistencies, it is better to explicitly use os.path.join to properly create paths, i.e you can use something like

with open(os.path.join(settings.BASE_DIR, '..', '..', 'package.json')) as package_json_file:

More info on join: https://docs.python.org/3/library/os.path.html#os.path.join

Upvotes: 2

Alasdair
Alasdair

Reputation: 308979

You can see the issue in the error message: src../../package.json - there is a forward slash missing in src...

Instead of concatenating strings, use os.path.join so that you don't have to worry about missing/duplicate forward slashes.

import os
os.path.join(settings.BASE_DIR, '../../package.json')

Upvotes: 4

Related Questions