[Answered ]-How to open files outside of the django project?

1πŸ‘

In /home/erwan/Images/eosya_app/backend/api/municipality/compute_municipality_view.py:

CURDIR = os.path.dirname(__file__)
FILES_DIR = os.path.join(CURDIR, '../../../database/unparsed_data/administrative_boundaries/')

...
with open(os.path.join(FILES_DIR, 'france-geojson-master/departements.geojson')) as fp:
    ...
πŸ‘€thebjorn

0πŸ‘

In your settings.py, you should have this line to define the BASE_DIR:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

Let’s assume your Django project structure is like this:

/home/erwan/Images/eosya_app/
  β”œβ”€β”€ backend/
  β”‚   β”œβ”€β”€ api/
  β”‚   β”‚   └── municipality/
  β”‚   β”‚       β”œβ”€β”€ compute_municipality_view.py
  β”‚   β”‚       └── ... (other files and folders)
  β”‚   └── ... (other files and folders)
  β”œβ”€β”€ database/
  β”‚   └── unparsed_data/
  β”‚       └── administrative_boundaries/
  β”‚           └── my_file.geojson
  └── eosya_app/
      β”œβ”€β”€ settings.py
      └── ... (other files and folders)

In the compute_municipality_view.py, you can access the Geojson file like this:

import os
from django.conf import settings

file_path = os.path.join(settings.BASE_DIR, 'database/unparsed_data/administrative_boundaries/my_file.geojson')

with open(file_path, 'r') as f:
    # Your file processing code here

By using settings.BASE_DIR, you are getting the base directory path of your Django project, and then you can construct the path to your Geojson file relative to that base directory.

πŸ‘€ANUPAMA T.M

Leave a comment