Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Loading files relative from project root

Tags:

python

oop

My project layout is as follows:

├ ...
├── pve
│   ├── blahblah
│   │   ├── TestDefinition.py
│   │   ├── TestDefinition.pyc
│   │   ├── __init__.py
│   │   └── __init__.pyc
│   └── pve.py
├── src
│   └── definitions
│       └── THISFILE.yml
└── ...

I need to be able to fetch files (THISFILE.yml for example) from src/definitions by the pve/blahblah/TestDefinition.py class.

How do I properly access the project root? Once I have that, I can access the .yml files relative. TIA.

like image 691
mr-sk Avatar asked Jan 23 '13 15:01

mr-sk


1 Answers

I like to create some sort of configuration file in the project root that has an aboslute path to the root. I do this only because the frameworks i usually use (django, scrapy) have some sort of convention like this

├ ...
├── pve
│   ├── blahblah
│   │   ├── TestDefinition.py
│   │   ├── TestDefinition.pyc
│   │   ├── __init__.py
│   │   └── __init__.pyc
│   └── pve.py
├── src
│   └── definitions
│       └── THISFILE.yml
└── settings.py



# settings.py

import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DEFINITIONS_ROOT = os.path.join(PROJECT_ROOT, 'src', 'definitions')


from myproject import settings 
settings.DEFINITIONS_ROOT
like image 80
dm03514 Avatar answered Oct 05 '22 15:10

dm03514