简体   繁体   中英

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 ?

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')

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, ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM