2

config.ini

[datasource]
host = localhost

config.py

import configparser
import os

config = configparser.ConfigParser()
config.read(os.path.join(os.getcwd(), 'config.ini'))
host = config['datasource']['host']

Test.py

import config
print(config.host)

Traceback (most recent call last):

File "Test\test.py", line 6, in

import config

File "C:\Users\jack\PycharmProjects\Test\config.py", line 6, in

host = config['datasource']['host']

File "C:\Users\jack\AppData\Local\Programs\Python\Python37-32\lib\configparser.py", line 958, in getitem

raise KeyError(key)

KeyError: 'datasource'

All the files are put in the same folder.

When I run Test.py script from the pycharm it does not have problem.

But when I calling from terminal the error come.

How to solve this problem?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Jack Lim
  • 195
  • 2
  • 5
  • 16
  • 1
    Presumably because the working directory is different, so `os.getcwd()` gives a different location. You almost certainly don't want to do that anyway. – Daniel Roseman Nov 09 '18 at 08:50
  • 1
    Print out `os.path.join(os.getcwd(), 'config.ini')` to see where Python is looking for your file there. – poke Nov 09 '18 at 08:54
  • `config.read(os.path.join(os.getcwd(), 'config.ini'))` won't raise any `OSError` even if the path is not exist. Instead it return [empty list](https://github.com/python/cpython/blob/master/Lib/configparser.py#L693). – Abdul Niyas P M Nov 09 '18 at 08:55
  • 1
    @DanielRoseman okay. The `os.getcwd()` point to the "C:\Users\jack\PycharmProjects\" and I change the path without using `os.getcwd()` and it works in terminal – Jack Lim Nov 09 '18 at 09:00

1 Answers1

0

If the config file is placed in the same directory

Just get the config.py file location, remove config.py file name and join with the config.ini file

path = '/'.join((os.path.abspath(__file__).replace('\\', '/')).split('/')[:-1])
config.read(os.path.join(path, 'config.ini'))

By this you not need keep changing the file path even you move the whole directory

Jack Lim
  • 195
  • 2
  • 5
  • 16
  • 1
    If `config.py` and `config.ini` are in the same directory, why you don't use `config.read('config.ini')`? – Lê Tư Thành Aug 15 '19 at 02:32
  • I try this before but it keep raise me the error so I leave my solution. If there is another best way to solve this then just go ahead with that – Jack Lim Aug 15 '19 at 02:40
  • 1
    ok, I have another suggestion for getting path above: `os.path.split(path_to_file)[0].replace('\\','/')`. This `os.path.split()` will split file path in to folder path and file name. – Lê Tư Thành Aug 15 '19 at 02:46