iniæ件ç®ä»
iniæ¯æ们常è§å°çé
ç½®æä»¶æ ¼å¼ä¹ä¸ã
iniæ¯å¾®è½¯Windowsæä½ç³»ç»ä¸çæ件æ©å±åï¼ä¹å¸¸ç¨å¨å
¶ä»ç³»ç»ï¼ã
INIæ¯è±æâåå§åï¼Initialï¼âç缩åãæ£å¦è¯¥æ¯è¯æ表示çï¼INIæ件被ç¨æ¥å¯¹æä½ç³»ç»æç¹å®ç¨åºåå§åæè¿è¡åæ°è®¾ç½®ã
ç¾åº¦ç¾ç§
éè¿å®ï¼å¯ä»¥å°ç»å¸¸éè¦æ¹åçåæ°ä¿åèµ·æ¥ï¼èä¸è¿å¯è¯»ï¼ï¼ä½¿ç¨åºæ´å ççµæ´»ã
æå
ç»åºä¸ä¸ªiniæ件ç示ä¾ã
[School]
ip = 10.15.40.123
mask = 255.255.255.0
gateway = 10.15.40.1
dns = 211.82.96.1
[Match]
ip = 172.17.29.120
mask = 255.255.255.0
gateway = 172.17.29.1
dns = 0.0.0.0
è¿ä¸ªé
ç½®æ件ä¸ä¿åçæ¯ä¸ååºåä¸çIP设置åæ°ã
ä¸é¢å°ä»¥çæå读åè¿ä¸ªé
ç½®æ件为ä¾ï¼è¿è¡è®²è§£ã
Pythonï¼v3ï¼è¯»åæ¹æ³
é¦å
ï¼Python读åinié
ç½®éè¦ç¨å°ConfigParserå
ï¼æ以è¦å
å è½½å®ã
import configparser
ä¹åæ们éè¦è½½å
¥é
ç½®æ件ã
config=configparser.ConfigParser()
#IpConfig.iniå¯ä»¥æ¯ä¸ä¸ªä¸åå¨çæ件ï¼æå³çåå¤æ°å»ºé
ç½®æ件ã
config.read("IpConfig.ini")
æ¥ä¸æ¥ï¼æ们å¯ä»¥ä½¿ç¨configparser.add_section()åé
ç½®æ件ä¸æ·»å ä¸ä¸ªSectionã
#æ·»å èSchool
config.add_section("School")
注æï¼å¦ææ件ä¸å·²ç»åå¨ç¸åºç项ç®ï¼åä¸è½åå¢å ååçèã
ç¶åå¯ä»¥ä½¿ç¨configparser.set()å¨èSchoolä¸å¢å æ°çåæ°ã
#æ·»å æ°çIPå°ååæ°
config.set("School","IP","192.168.1.120")
config.set("School","Mask","255.255.255.0")
config.set("School","Gateway","192.168.1.1")
config.set("School","DNS","211.82.96.1")
ä½ å¯ä»¥ä»¥åæ ·çæ¹å¼å¢å å
¶å®å 项ã
#ç±äºiniæ件ä¸å¯è½æåå项ï¼æ以åäºå¼å¸¸å¤ç
try:
config.add_section("Match")
config.set("Match","IP","172.17.29.120")
config.set("Match","Mask","255.255.255.0")
config.set("Match","Gateway","172.17.29.1")
config.set("Match","DNS","0.0.0.0")
except configparser.DuplicateSectionError:
print("Section 'Match' already exists")
å¢å å®ææéè¦ç项ç®åï¼è¦è®°å¾ä½¿ç¨configparser.write()è¿è¡åå
¥æä½ã
config.write(open("IpConfig.ini", "w"))
以ä¸å°±æ¯åå
¥é
ç½®æ件çè¿ç¨ã
æ¥ä¸æ¥æ们使ç¨configparser.get()读ååæåå
¥é
ç½®æ件ä¸çåæ°ã读åä¹åè¦è®°å¾è¯»åiniæ件ã
ip=config.get("School","IP")
mask=config.get("School","mask")
gateway=config.get("School","Gateway")
dns=config.get("School","DNS")
print((ip,mask+"\n"+gateway,dns))
å®æ´ç¤ºä¾
ä¸é¢æ¯ä¸ä¸ªå®æ´ç示ä¾ç¨åºï¼ä»å°çæä¸ä¸ªIpConfig.iniçé
ç½®æ件ï¼å读åæ件ä¸çæ°æ®ï¼è¾åºå°å±å¹ä¸ã
# -*- coding: utf-8 -*-
import configparser
#读åé
ç½®æ件
config=configparser.ConfigParser()
config.read("IpConfig.ini")
#åå
¥å®¿èé
ç½®æ件
try:
config.add_section("School")
config.set("School","IP","10.15.40.123")
config.set("School","Mask","255.255.255.0")
config.set("School","Gateway","10.15.40.1")
config.set("School","DNS","211.82.96.1")
except configparser.DuplicateSectionError:
print("Section 'School' already exists")
#åå
¥æ¯èµé
ç½®æ件
try:
config.add_section("Match")
config.set("Match","IP","172.17.29.120")
config.set("Match","Mask","255.255.255.0")
config.set("Match","Gateway","172.17.29.1")
config.set("Match","DNS","0.0.0.0")
except configparser.DuplicateSectionError:
print("Section 'Match' already exists")
#åå
¥é
ç½®æ件
config.write(open("IpConfig.ini", "w"))
ip=config.get("School","IP")
mask=config.get("School","mask")
gateway=config.get("School","Gateway")
dns=config.get("School","DNS")
print((ip,mask+"\n"+gateway,dns))
温馨提示:答案为网友推荐,仅供参考