首页 > 解决方案 > 配置解析器打开文件但不返回任何内容?

问题描述

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

我的代码:

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()”只返回一个空列表?我很困惑,我确信这是我所缺少的非常简单的东西......任何帮助将不胜感激。

标签: pythonpython-3.xconfigparser

解决方案


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

返回可用部分的列表;默认部分不包含在列表中。 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']

推荐阅读