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
-
related: stackoverflow.com/q/1810743/6464041Gábor Fekete– Gábor Fekete2020年07月21日 10:58:31 +00:00Commented Jul 21, 2020 at 10:58
2 Answers 2
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
Comments
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')
6 Comments
os.path.dirname will just remove the '/..' from the end (which will in fact be a deeper directory than if you didn't join on the '..' in the first place). If you actually want one level higher, then maybe you could use os.path.dirname(os.path.dirname(os.path.abspath(__file__))).os.path.dirnameshould be use inside os.path.join. Correcting my codedirname(dirname(...)) is what I do in practice with operational code where a package has some scripts inside a scripts subdirectory and these scripts need the path of the top-level directory of the package. It has always worked fine, but if you have a neater solution, I'll be interested to see it.os.path.dirname(os.path.abspath(__file__)) will give you directory in which script marked by __file__ is lokated. What you really need is to go one directory up. This can always be achieved by calling os.path.join(<path>,'..' as long as you're not in root directory. Although dirname(dirname(<path_to_file>) also works as dirname simply uses split on path and gets first argument