当前位置: 动力学知识库 > 问答 > 编程问答 >

python - 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?

网友答案:

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"))
分享给朋友:
您可能感兴趣的文章:
随机阅读: