Aniket Banyal
Aniket Banyal

Reputation: 452

Save file in directory of executing file

I have a directory (data) that contains a file get_raw_data.py. get_raw_data.py has a function to save a file.

A file present in some other directory (stock_prediction) imports this function and runs it.

The file gets saved in the stock_prediction directory.

How do I save the file in data directory? (stock_prediction has a child directory dashboard which has the child directory data)

I could use absolute path but is there a better way?

Upvotes: 1

Views: 3097

Answers (1)

Peter Badida
Peter Badida

Reputation: 12199

You can create the path relatively to a file where this code is present i.e. if your file is hello.py, the __file__ will be its location:

from os.path import abspath, dirname, join

path = join(dirname(abspath(__file__)), "folder", "file.txt")
print(path)

Example:

# if run from get_raw_data.py
print(__file__)                                        # get_raw_data.py
print(dirname(abspath(__file__)))                      # "data" folder
print(join(dirname(abspath(__file__)), "output.txt"))  # output.txt in "data"

and based on that you can navigate anywhere if you have a permission to access/write to such location.

Also you can utilize os.makedirs(dirname(path)) to create such a location if it has folders not yet present and then write to it:

with open(path, "w"):
    ...

Upvotes: 3

Related Questions