tubs
tubs

Reputation: 151

Opening a file in a module regardless of current working directory

I have a module that deals with a database with the database inside the module directory, the file structure is as follows

app/
  foo.py
  database/
    __init__.py
    bar.py
    database.db

Inside my bar.py file I have:

open("database.db")

When I import this database module it gives an error because the database.db file cannot be found, but it works when I use open("database/database.db"). Is there a way that I can open this file from any other directory and have the module access the file correctly?

Upvotes: 2

Views: 293

Answers (1)

zaquest
zaquest

Reputation: 2050

You can use __file__. It keeps path to current python file. For example your bar.py file could contain something like this

from os import path
open(path.join(path.dirname(__file__), "database.db"))

Upvotes: 3

Related Questions