当需要使用python读取配置文件时,需要使用到python的ConfigParser模块。下面举个栗子。

首先创建init格式的配置文件0.init:

[global]
id = 0
object_x = 0.003

[world]
id = 12
object_x = 0.14

在python中读取并使用配置文件中的内容:

#! /usr/bin/python

import ConfigParser

config = ConfigParser.ConfigParser()
config.readfp(open("0.ini"),"rb")

object_id = int(config.get("global","id"))
object_x = config.get("global","object_x")

print type(object_id), object_id
print type(object_x), object_x

world_id = int(config.get("world","id"))
world_x = config.get("world","object_x")

print type(world_id), world_id
print type(world_x), world_x

输出结果为:

<type 'int'> 0
<type 'str'> 0.003
<type 'int'> 12
<type 'str'> 0.14



Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐