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