配置解析器打开文件但不返回任何内容?

问题描述

我正尝试像往常一样使用配置解析器,但是由于某种原因我没有提取任何部分?

我的代码

import os,configparser

## Get directory path
dir_path = os.path.dirname(os.path.realpath(__file__))
file_path = dir_path + "\\development.ini"

## Setup config parser object
config = configparser.ConfigParser()

## Read file into config parser
with open(file_path) as file:
    config.read_file(file)

print(config.sections())

我的配置文件

[MysqL]
Host = 192.168.1.11
Port = 3306
Username = server
Password = (Removed)
Database = server

代码输出

[]

没有错误,并且在“ config.sections()”上仅返回一个空列表?我很困惑,我确定这很简单,我很想念...任何帮助将不胜感激。

解决方法

这是因为您只有默认部分。根据文档:

返回可用部分的列表; 默认部分未包含在列表中https://docs.python.org/3/library/configparser.html

然后,您不必打开文件。配置解析器将为您完成此任务。

## Setup config parser object
config = configparser.ConfigParser()

## Read file into config parser
config.read(file)

print(config.sections())

这是一个例子:

config.ini

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

test.py

import configparser
config = configparser.ConfigParser()
config.read('config.ini')
print(config.sections())

输出:

['bitbucket.org','topsecret.server.com']
,

我认为问题仅在于访问文件。我尝试使用下面的代码将两个文件放在一个文件夹中,运行正常。尝试更改为.cfg

from configparser import ConfigParser

config = ConfigParser()
config.read("dev.cfg")

print(config.sections())

或您的代码

import os,configparser

## Get directory path
dir_path = os.path.dirname(os.path.realpath(__file__))
file_path = dir_path + "\\dev.cfg"

## Setup config parser object
config = configparser.ConfigParser()

## Read file into config parser
with open(file_path) as file:
    config.read_file(file)

print(config.sections())