Reputation: 21
Firstly, the directory.
file1.py
|
| --__init__.py
file2.py
some_package
|
| --__init__.py
config.py
settings.ini
other_package
|
| --__init__.py
access.py
Now, in config.py
, there's a function, readfromsetting()
, which reads settings.ini
and returns the content inside. In access.py
, i've imported config.py
(No, it's not what you're thinking, access.py
successfully imports config.py
), and tried calling readfromsetting()
function, but Python throws error.
No such file or directory, "settings.ini"
So, my question is, how can I read the content of settings.ini
, from access.py
using config.py
?
My config.py
:
def readfromsetting():
with open('settings.py', 'r') as file:
return file.read()
My access.py
from some_package import config
def get_setting():
return config.readfromsetting()
Upvotes: 0
Views: 32
Reputation: 1024
Your problem is here:
def readfromsetting():
with open('settings.ini', 'r') as file:
return file.read()
'settings.ini' is a relative path. This works perfect if the file your are looking for is in the same directory. Since you call this method from access.py and access.py resides not in this directory, it cannot find the settings.ini file.
I recommend you use instead an absolute path for the settings.ini file in your open method. If you are sure that you only call this method from within access.py, you can also edit __file__
like mentioned in the other answer.
Upvotes: 0
Reputation: 90999
When you do import <some script>
python looks inside the contents of sys.path
to import the python script . But when you are reading files using open()
or other methods, and you give relative paths, Python would try to resolve the path as relative to the current working directory, it would not look inside the directory in which you script resides (unless that is the working directory).
You should not depend on relative paths, instead you should try giving absolute paths, where possible.
In your case, if you are sure that the directory structure would not change (that is settings.ini
would always be in the directory in which config.py
exists or settings.py
exists) , you can use __file__
variable to access the path of the file, and then use that to create absolute path to your settings.ini
. Example -
import os.path
dirpath = os.path.abspath(os.path.dirname(__file__))
settings_file = os.path.join(dirpath,'settings.ini')
Upvotes: 2