共計 782 個字符,預計需要花費 2 分鐘才能閱讀完成。
Python 提供了一個標準庫 configparser
用于讀取和修改 INI 文件。
首先,需要導入 configparser
模塊:
import configparser
然后,創建一個 ConfigParser
對象,并使用 read()
方法讀取 INI 文件:
config = configparser.ConfigParser()
config.read('config.ini')
可以使用 get()
方法獲取指定 section 和 option 的值:
value = config.get('section', 'option')
也可以使用 sections()
方法獲取所有的 section 列表:
sections = config.sections()
對于一個 section,可以使用 options()
方法獲取所有的 option 列表:
options = config.options('section')
完整的示例代碼如下:
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# 獲取指定 section 和 option 的值
value = config.get('section', 'option')
print(value)
# 獲取所有的 section 列表
sections = config.sections()
print(sections)
# 獲取指定 section 的所有 option 列表
options = config.options('section')
print(options)
需要注意的是,讀取 INI 文件時,section 和 option 都是大小寫敏感的。如果讀取的 section 或 option 在 INI 文件中不存在,則會拋出 NoSectionError
或NoOptionError
異常。
丸趣 TV 網 – 提供最優質的資源集合!
正文完