Python ConfigParser无法正确搜索.ini文件(Ubuntu 14,Python 3.4)

Python ConfigParser无法正确搜索.ini文件(Ubuntu 14,Python 3.4),python,Python,问题: 代码编译得很好,但每次调用read_db_config函数时,我都会得到“Exception:mysql未在mysql_config.ini文件中找到” 该文件位于同一目录中,但主脚本使用 import sys from Config.MySQL.python_mysql_dbconfig import read_db_config 我是python新手,到处都搜索过,但我似乎无法指出我的问题 代码: mysql_config.ini: [mysql] database = test

问题: 代码编译得很好,但每次调用read_db_config函数时,我都会得到“Exception:mysql未在mysql_config.ini文件中找到”

该文件位于同一目录中,但主脚本使用

import sys 
from Config.MySQL.python_mysql_dbconfig import read_db_config
我是python新手,到处都搜索过,但我似乎无法指出我的问题

代码:

mysql_config.ini:

[mysql]
database = testdba
user = root
password = test
unix_socket = /opt/lampp/var/mysql/mysql.sock

我再次运行了它,但修改为添加

parser = configparser.ConfigParser()
parser['mysql'] = {'database': 'testdba',
                   'user' : 'root',
                   'password' : 'test',
                   'unix_socket' : '/opt/lampp/var/mysql/mysql.sock'}
with open('mysql_config.ini', 'w') as configfile:
parser.write(configfile
我发现这创建了文件“mysql_config.ini”,它不在存储python“read_db_config”的目录中,而是在调用该模块的主python模块的父目录中。我搜索了一下,找到了一个永久性的解决方案,可以让“mysql_config.ini”保留在我想要的地方

import configparser 

def read_db_config(dirname = '/opt/Python_MySQL_Email_Receipt_Client/Config/MySQL/', filename='mysql_config.ini', section='mysql'):

# create parser and read ini configuration file

parser = configparser.ConfigParser()
parser.read(dirname + filename)

# get section, default to mysql
db = {}
if parser.has_section(section):
    items = parser.items(section)
    for item in items:
        db[item[0]] = item[1]
else:
    raise Exception('{0} not found in the {1} file'.format(section, filename))

return db
如果对文件或目录名使用相对路径,python将在当前工作目录(bash中的
$PWD
变量)中查找(或创建)它们

如果希望它们与当前python文件相关,可以使用(python 3.4)

或(python 2.7)

如果您的
mysql_config.ini
文件位于python脚本下面的
etc
目录中


当然,您可以始终使用绝对路径(从一个
/
开始,即
/home/someuser/mysql_config.ini
)。

谢谢,这将使它更干净
import configparser 

def read_db_config(dirname = '/opt/Python_MySQL_Email_Receipt_Client/Config/MySQL/', filename='mysql_config.ini', section='mysql'):

# create parser and read ini configuration file

parser = configparser.ConfigParser()
parser.read(dirname + filename)

# get section, default to mysql
db = {}
if parser.has_section(section):
    items = parser.items(section)
    for item in items:
        db[item[0]] = item[1]
else:
    raise Exception('{0} not found in the {1} file'.format(section, filename))

return db
from pathlib import Path
HERE = Path(__file__).parent.resolve()
CONFIG_PATH = HERE / '../etc/mysql_config.ini'
import os.path
HERE = os.path.abspath(os.path.dirname(__file__))
CONFIG_PATH = os.path.join(HERE, '../etc/mysql_config.ini')