#!/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