python - 配置解析器打开文件但不返回任何内容?
问题描述
我正在尝试像往常一样使用配置解析器,但由于某种原因我没有拉出任何部分?
我的代码:
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']
推荐阅读
- javascript - 无法在three.js中将纹理映射到网格
- gnuplot - 如何在gnuplot中绘制由部件定义的表面
- angular - Angular 6 - 接收电子邮件的自定义验证器始终返回 true
- javascript - 如何使用聚合物 3 正确定义 node_modules 的路径
- spring-boot - DateTimeFormatter.ISO_OFFSET_DATE_TIME 未按预期工作
- php - 使用 pimple 时在构造函数中注入
- javascript - 将 map() 与具有两个参数的函数一起使用
- corda - CollectSignaturesFlow 中的流异常
- python - pandas.dataframe.fillna: NotImplementedError
- python - 我如何用python循环网络抓取?