python 작업 ini 형식 설정 파일 의 인 스 턴 스 튜 토리 얼

6839 단어 pythonini유형
1.ini 파일 소개
INI 파일 형식 은 일부 플랫폼 이나 소프트웨어 에 있 는 프로필 의 비공 식 기준 으로 절(section)과 키(key)로 구성 되 어 마이크로소프트 윈도 운영 체제 에 자주 사용 된다.이 프로필 의 파일 확장 자 는 대부분 INI 입 니 다.
2.ini 파일 의 구조
단편[섹 션]키 이름 option값 value3.실례:
실례 1
python25.ini

[teachers]
name = ['yushen', 'pianpian']
age = 16
gender = ' '
favor = {"movie": "  ", "music": "   "}

[student]
name = ['    ', '    ']
age = 18
작업 ini 파일

from configparser import ConfigParser

#    
config = ConfigParser()

#     
config.read('python25.ini', encoding='utf-8')

a = config.get('teachers', 'name')
print(a)
print(type(a))
실행 결 과 는 다음 과 같 습 니 다.

실례 2
fz.ini

fz.ini 파일 코드 읽 기:

import configparser
import os

curpath = os.path.dirname(os.path.realpath(__file__))
cfgpath = os.path.join(curpath, "fz.ini")

# fz.ini   
print(cfgpath)

#       
conf = configparser.ConfigParser()

#  ini  
conf.read(cfgpath, encoding="utf-8")


#      section
sections = conf.sections()
#   list
print(sections)

items = conf.items('oracle')
# list       
print(items)
실행 결과:

인 스 턴 스 3,패키지 업그레이드
set 수정,add 추가,쓰기,쓰기,remove 삭제
이 패 키 지 는 다음 과 같은 기능 을 수행 합 니 다:
섹 션 목록 가 져 오기지정 한 section 의 options 목록 가 져 오기지 정 된 섹 션 의 설정 정보 목록 가 져 오기유형 별로 설정 정 보 를 읽 습 니 다신규 섹 션지 정 된 option 값 을 설정 합 니 다지정 섹 션 삭제지 정 된 옵션 삭제

# -*- coding:utf-8 -*-

from configparser import ConfigParser
import os


class TEINI:
 def __init__(self, path):
  self.path = path
  self.ini = ConfigParser()
  self.ini.read(self.path)


 #   sections  
 def get_sections(self):
  if self.ini:
   return self.ini.sections()

 #      section options  
 def get_options_by_section(self, section):
  if self.ini:
   return self.ini.options(section)

 #     section       
 def get_section_items(self, section):
  if self.ini:
   return self.ini.items(section)

 #          
 #        
 def get_string(self, section, option):
  if self.ini:
   return self.ini.get(section, option)

 #   int  
 def get_int(self, section, option):
  if self.ini:
   return self.ini.getint(section, option)

 #   float  
 def get_float(self, section, option):
  if self.ini:
   return self.ini.getfloat(section, option)

 #   bool  
 def get_boolean(self, section, option):
  if self.ini:
   return self.ini.getboolean(section, option)

 #   section
 def add_section(self, section):
  if self.ini:
   self.ini.add_section(section)
   self.ini.write(open(self.path, "w"))

 #     option 
 def set_option(self, section, option, value):
  if self.ini:
   self.ini.set(section, option, value)
   self.ini.write(open(self.path, "w"))

 #     section
 def remove_section(self, section):
  if self.ini:
   self.ini.remove_section(section)
   self.ini.write(open(self.path, "w"))

 #     option
 def remove_option(self, section, option):
  if self.ini:
   self.ini.remove_option(section, option)
   self.ini.write(open(self.path, "w"))


if __name__ == "__main__":
 print("python ini       ======        !!!")

 #     mysql.ini   ,         
 if os.path.exists("mysql.ini"):
  os.remove("mysql.ini")

 #          mysql.ini 
 ini = TEINI("mysql.ini")

 #     mysql section
 mysql_section = "mysql"
 ini.add_section(mysql_section)

 #  mysql section         
 ini.set_option(mysql_section, "host", "192.168.3.1")
 ini.set_option(mysql_section, "port", "3306")
 ini.set_option(mysql_section, "db", "mysql")
 ini.set_option(mysql_section, "user", "admin")
 ini.set_option(mysql_section, "password", "111111")

 #      oracle section
 oracle_section = "oracle"
 ini.add_section(oracle_section)

 # oracle section         
 ini.set_option(oracle_section, "host", "192.172.0.1")
 ini.set_option(oracle_section, "port", "8080")
 ini.set_option(oracle_section, "db", "oracle")
 ini.set_option(oracle_section, "user", "guiyin")
 ini.set_option(oracle_section, "password", "666666")

 #       section,  console  
 sections = ini.get_sections()
 print(sections)

 #     section  options,  console   
 print("===" * 20)
 for sec in sections:
  print(sec, "   options : ")
  options = ini.get_options_by_section(sec)
  print(options)
  print("===" * 20)

 #     section      
 for sec in sections:
  print(sec, "        : ")
  items = ini.get_section_items(sec)
  print(items)
  print("***" * 20)

 #      option       host port
 host = ini.get_string("mysql", "host")
 port = ini.get_int("mysql", "port")
 print("  : ", type(host), " ", type(port))
 print(host, " ", port)

 #   mysql  host  
 ini.remove_option("mysql", "host")

 #   oracle section
 ini.remove_section("oracle")

 #   mysql port   4000
 ini.set_option("mysql", "port", "5538")


 #   mysql.ini        
 # [mysql]
 # port = 5538
 # db = mysql
 # user = admin
 # password = 111111
items = ini.get_section_items("mysql")
print(items)
print("!!!" * 20)

실행 결 과 는 다음 과 같 습 니 다.

총결산 
python 작업 ini 형식 프로필 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 python 작업 ini 형식 프로필 내용 은 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많은 지원 바 랍 니 다!

좋은 웹페이지 즐겨찾기