Python读写ini文件


搬运地址: https://www.jb51.net/article/66902.htm

比如有一个文件update.ini,里面有这些内容:

1
2
3
4
5
6
7
8
[ZIP]
EngineVersion=0
DATVersion=5127
FileName=dat-5127.zip
FilePath=/pub/antivirus/datfiles/4.x/
FileSize=13481555
Checksum=6037,021E
MD5=aaeb519d3f276b810d46642d782d8921

那就可以通过下面这些代码得到MD5的值,简单吧

1
2
3
4
5
6
7
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp( open ( 'update.ini' ))
a = config.get( "ZIP" , "MD5" )
print a

写也很简单:

1
2
3
4
5
6
7
8
9
10
import ConfigParser
config = ConfigParser.ConfigParser()
# set a number of parameters
config.add_section( "book" )
config. set ( "book" , "title" , "the python standard library" )
config. set ( "book" , "author" , "fredrik lundh" )
config.add_section( "ematter" )
config. set ( "ematter" , "pages" , 250 )
# write to file
config.write( open ( '1.ini' , "w" ))

修改也不难(添加内容):

1
2
3
4
5
6
7
8
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ConfigParser
config = ConfigParser.ConfigParser()
config.read( '1.ini' )
a = config.add_section( "md5" )
config. set ( "md5" , "value" , "1234" )
config.write( open ( '1.ini' , "r+" )) #可以把r+改成其他方式,看看结果:)

修改内容:

1
2
3
4
5
6
7
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ConfigParser
config = ConfigParser.ConfigParser()
config.read( '1.ini' )
config. set ( "md5" , "value" , "kingsoft" ) #这样md5就从1234变成kingsoft了
config.write( open ( '1.ini' , "r+" ))

 

读写.ini文件的类

from configparser import ConfigParser
import os
from demo import settings # django项目的配置文件


class ReadWriteConfFile(object):
path = settings.BASE_DIR + os.sep + 'config.ini' # 可根据需要替换成自己的路径

@staticmethod
def get_parser():
cf = ConfigParser()
cf.read(ReadWriteConfFile.path, encoding='utf-8')
return cf

@staticmethod
def write_parser(cf):
f = open(ReadWriteConfFile.path, "w", encoding='utf-8')
cf.write(f)
f.close()

@staticmethod
def add_section(section):
cf = ReadWriteConfFile.get_parser()
all_sections = cf.sections()
if section in all_sections:
return
else:
cf.add_section(section)
ReadWriteConfFile.write_parser(cf)

@staticmethod
def get_option(section, key):
cf = ReadWriteConfFile.get_parser()
return cf.get(section, key)

@staticmethod
def set_option(section, key, value):
cf = ReadWriteConfFile.get_parser()
cf.set(section, key, value)
ReadWriteConfFile.write_parser(cf)


if __name__ == '__main__':
ReadWriteConfFile.add_section('messages')
ReadWriteConfFile.set_option('messages', 'name', 'sophia')
x = ReadWriteConfFile.get_option('messages', 'name')
print(x)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM