Python读写ini文件

#!/usr/bin/env python
# 1.py
# use UTF-8
# Python 3.3.0

# ini文件的读和写
import configparser  # python自带的库
import os

# 枚举dirPath目录下的所有文件
def WriteINI(strIniPath):
#begin
	config = configparser.ConfigParser()
	config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'}
	config['bitbucket.org'] = {}
	config['bitbucket.org']['User'] = 'hg'
	config['topsecret.server.com'] = {}
	topsecret = config['topsecret.server.com']
	topsecret['Port'] = '50022'     # mutates the parser
	topsecret['ForwardX11'] = 'no'  # same here
	config['DEFAULT']['ForwardX11'] = 'yes'
	with open(strIniPath, 'w') as configfile:
	#begin
	  config.write(configfile)
	#end
#end

def ReadINI(strIniPath):
#begin
	config = configparser.ConfigParser()
	config.sections()
	config.read('example.ini')
	config.sections()
	'bitbucket.org' in config
	'bytebong.com' in config
	config['bitbucket.org']['User']
	config['DEFAULT']['Compression']
	topsecret = config['topsecret.server.com']
	topsecret['ForwardX11']
	topsecret['Port']
	for key in config['bitbucket.org']:
	#begin
		print(key)
	#end
	config['bitbucket.org']['ForwardX11']
#end


def main():
#begin
	WriteINI('example.ini')
	ReadINI('example.ini')
	os.system("pause")
#end

if __name__ == '__main__':
#begin
	main()
#end

# 输出:
# user
# compressionlevel
# compression
# serveraliveinterval
# forwardx11


#!/usr/bin/env python
# Python 2.7.3
# 2.py

# ini文件的读和写
import ConfigParser
import os

# 枚举dirPath目录下的所有文件
def WriteINI(strIniPath):
	config = ConfigParser.ConfigParser()
	
	config.add_section("DEFAULT1")
	config.set("DEFAULT1", "compressionlevel", "9")
	config.set("DEFAULT1", "compression", "yes")
	config.set("DEFAULT1", "serveraliveinterval", "45")
	config.set("DEFAULT1", "forwardx11", "yes")
	
	config.add_section("bitbucket.org")
	config.set("bitbucket.org", "user", "hg")

	config.add_section("topsecret.server.com")
	config.set("topsecret.server.com", "port", "50022")
	config.set("topsecret.server.com", "forwardx11", "no")

	f = open(strIniPath, "w")
	config.write(f)     # 保存ini文件
	f.close()


def ReadINI(strIniPath):
	config = ConfigParser.ConfigParser()
	config.read(strIniPath)
	ip = config.get("DEFAULT1","serveraliveinterval") # 获取ip值 
	print(ip)

def main():
	WriteINI('example.ini')
	ReadINI('example.ini')
	os.system("pause")

if __name__ == '__main__':
	main()


ini文件:

[DEFAULT1]
compressionlevel = 9
compression = yes
serveraliveinterval = 45
forwardx11 = yes


[bitbucket.org]
user = hg


[topsecret.server.com]
port = 50022
forwardx11 = no


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值