Reputation: 1680
I am currently working inside the folder product_graph_analysis
, specifically inside the file "database_functions.py"
and when I configure my base directory:
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
whenever I want to set a path_file:
path_file = os.path.join(BASE_DIR, 'my_file.csv')
The program will look inside the folder product_graph_analysis.
I would like to set a path_file or base directory in the "mother_folder", the one that contains "csv" and "product_graph_analysis", in this way I could access all folders of my project from within database_functions.py
Upvotes: 0
Views: 2391
Reputation: 1680
Well, I found a solution for this particular case that works fine:
import os
file='csv/my_file.csv'
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
HOME_DIR = BASE_DIR.replace('/product_graph_analysis', '')
path_file = os.path.join(HOME_DIR, file)
Output:
>>> print(BASE_DIR)
'/home/mother_folder/product_graph_analysis'
>>> print(HOME_DIR)
'/home/mother_folder'
If yo know a 'better'/'more elegant' option let me know
Upvotes: 1
Reputation: 5709
So, you want to have BASE_DIR
one directory up, right? Try this one
BASE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
Assuming this line is located in database_functions.py
, with this statement you explicitly set BASE dir to the directory one level up (i.e. <directory of database_functions.py>/..
) than the one in which database_functions.py
is located specified by __file__
location.
Please note that this will affects all usages of BASE_DIR
Now whenever you want to open any file located in CSV
subdirectory you should also set it appropriately e.g.
path_file = os.path.join(BASE_DIR, 'CSV', 'my_file.csv')
Upvotes: 0