Home > Backend Development > Python Tutorial > python中ConfigParse模块的用法

python中ConfigParse模块的用法

WBOY
Release: 2016-06-16 08:41:28
Original
1617 people have browsed it

本文实例讲述了python中ConfigParse模块的用法,分享给大家供大家参考。具体方法如下:

写配置一般用ConfigParse.RawConfigParse类

读配置用ConfigParse.ConfigParse类

代码如下:

写配置文件:

import ConfigParser 
import time  
config = ConfigParser.RawConfigParser() 
 
task = {} 
task["id"] = 1 
task["package"] = "exe" 
task["timeout"] = 150 
task["dst_filename"] = "1.exe" 
task["custom"] = "" 
config.add_section("analysis")#增加section 
config.set("analysis", "id", task["id"])#增加option 
config.set("analysis", "target", task["dst_filename"]) 
config.set("analysis", "package", task["package"]) 
config.set("analysis", "timeout", task["timeout"]) 
config.set("analysis", "started", time.asctime()) 
fp = open("analy.conf", "w") 
config.write(fp)#写入文件中 

Copy after login

运行结果如下:

[analysis]
started = Tue Apr 10 15:40:51 2012
package = exe
id = 1
timeout = 150
target = 1.exe

Copy after login

读取配置文件:

import ConfigParser 
 
config = ConfigParser.ConfigParser() 
 
config.read("analy.conf") 
if config.has_option("analysis", "timeout"): 
  print config.get("analysis", "timeout") 
   
print config.sections() 
print config.get("analysis", "package") 
print config.getint("analysis", "id") 

Copy after login

打印结果如下:

150
['analysis']
exe
1
Copy after login

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template