用python读取config.ini内容

Python评论335阅读模式
摘要

在Python中,可以使用ConfigParser模块来读取配置文件的内容。以下是一个示例:

假设我们有一个名为config.ini的配置文件,其内容如下:

[database]
host = localhost
port = 3306
username = root
password = 123456
database = mydb

我们可以使用以下代码来读取配置文件的内容:文章源自爱尚资源教程网-https://www.23jcw.net/5768.html

import configparser

config = configparser.ConfigParser()
config.read('config.ini')

host = config.get('database', 'host')
port = config.get('database', 'port')
username = config.get('database', 'username')
password = config.get('database', 'password')
database = config.get('database', 'database')

print(host, port, username, password, database)

输出结果为:文章源自爱尚资源教程网-https://www.23jcw.net/5768.html

localhost 3306 root 123456 mydb

在这个示例中,我们首先导入了ConfigParser模块,然后创建了一个ConfigParser对象。文章源自爱尚资源教程网-https://www.23jcw.net/5768.html

接着,我们使用read()方法读取了配置文件的内容,并使用get()方法获取了配置文件中的值。文章源自爱尚资源教程网-https://www.23jcw.net/5768.html

最后,我们将这些值打印出来。文章源自爱尚资源教程网-https://www.23jcw.net/5768.html 文章源自爱尚资源教程网-https://www.23jcw.net/5768.html

相关文章
版权声明:文章图片资源来源于网络,如有侵权,请留言删除!!!
  • 温馨提示:如遇到资源下载不了,或者文章没有解决你的问题的,可以联系我们帮你处理!!!
  • 转载请务必保留本文链接:https://www.23jcw.net/5768.html

发表评论