本文章介绍了如何使用Python语言来有效地读取、解析和修改常见的配置文件格式(如INI, JSON等),帮助开发者轻松管理复杂的系统参数。
*.cfg文件通常是程序运行的配置文件,在Python中读取和编写这类文件可以使用ConfigParser模块。下面通过一个例子来展示如何在Python中解析配置文件。
首先来看一下创建或更新.cfg文件的基本代码:
```python
# -*- coding: UTF-8 -*-
import os
import ConfigParser
CONFIG_FILE = config.cfg
if __name__ == __main__:
config = ConfigParser.ConfigParser()
# 写入默认的设置值到配置文件中,如果该文件不存在的话。
if not os.path.exists(CONFIG_FILE):
config.add_section(Server)
config.set(Server, host, 127.0.0.1)
config.set(Server, port, 5432)
# 数据库设置
config.add_section(Database)
config.set(Database, name, DATABASE_NAME)
config.set(Database, username, postgres)
config.set(Database, password, postgres)
with open(CONFIG_FILE, mode=w) as f:
config.write(f)
```
这段代码会创建一个名为`config.cfg`的配置文件,并设置一些基本的服务器和数据库连接信息。如果该文件已经存在,则不会覆盖它,而是保留原有的内容。
解析这个配置文件的内容可以使用类似的ConfigParser方法来读取:
```python
import ConfigParser
# 加载已存在的cfg文件以获取其值。
config = ConfigParser.ConfigParser()
config.read(CONFIG_FILE)
host = config.get(Server, host)
port = config.getint(Server, port)
db_name = config.get(Database, name)
username = config.get(Database, username)
password = config.get(Database, password)
print(Host: %s, Port: %d % (host, port))
```
以上代码展示了如何读取配置文件中的设置值,并将这些信息用于程序的其他部分。