2012-01-16 249 views
59

我需要使用Python3讀取,編寫和創建一個INI文件。如何使用Python3讀寫INI文件?

FILE.INI

default_path = "/path/name/" 
default_file = "file.txt" 

Python的文件:

# read file and if not exists 
ini = iniFile('FILE.INI') 

# Get and Print Config Line "default_path" 
getLine = ini.default_path 

# Print (string)/path/name 
print getLine 

# Append new line and if exists edit this line 
ini.append('default_path' , 'var/shared/') 

ini.append('default_message' , 'Hey! help me!!') 

UPDATE FILE.INI

default_path = "var/shared/" 
default_file = "file.txt" 
default_message = "Hey! help me!!" 
+4

http://docs.python.org/library/configparser.html? – 2012-01-16 17:57:30

+2

其實,http://stackoverflow.com/a/3220891/716118怎麼樣? – voithos 2012-01-16 18:01:01

回答

89

這可有得開始:

import configparser 

config = configparser.ConfigParser() 
config.read('FILE.INI') 
print(config['DEFAULT']['path'])  # -> "/path/name/" 
config['DEFAULT']['path'] = '/var/shared/' # update 
config['DEFAULT']['default_message'] = 'Hey! help me!!' # create 

with open('FILE.INI', 'w') as configfile: # save 
    config.write(configfile) 

你可以找到更多的official configparser documentation

37

這是一個完整的讀取,更新和寫入示例。

輸入文件,test.ini

[section_a] 
string_val = hello 
bool_val = false 
int_val = 11 
pi_val = 3.14 

工作代碼。

try: 
    from configparser import ConfigParser 
except ImportError: 
    from ConfigParser import ConfigParser # ver. < 3.0 

# instantiate 
config = ConfigParser() 

# parse existing file 
config.read('test.ini') 

# read values from a section 
string_val = config.get('section_a', 'string_val') 
bool_val = config.getboolean('section_a', 'bool_val') 
int_val = config.getint('section_a', 'int_val') 
float_val = config.getfloat('section_a', 'pi_val') 

# update existing value 
config.set('section_a', 'string_val', 'world') 

# add a new section and some values 
config.add_section('section_b') 
config.set('section_b', 'meal_val', 'spam') 
config.set('section_b', 'not_found_val', 404) 

# save to a file 
with open('test_update.ini', 'w') as configfile: 
    config.write(configfile) 

輸出文件,test_update.ini

[section_a] 
string_val = world 
bool_val = false 
int_val = 11 
pi_val = 3.14 

[section_b] 
meal_val = spam 
not_found_val = 404 

原始輸入文件保持不變。

3

標準ConfigParser通常需要通過config['section_name']['key']訪問,這是沒有趣。稍加修改可以提供屬性的訪問:

class AttrDict(dict): 
    def __init__(self, *args, **kwargs): 
     super(AttrDict, self).__init__(*args, **kwargs) 
     self.__dict__ = self 

AttrDict是從dict派生的類,它允許經由兩個字典鍵訪問和屬性訪問:這意味着a.x is a['x']

我們所用ConfigParser使用這個類:

config = configparser.ConfigParser(dict_type=AttrDict) 
config.read('application.ini') 

,現在我們得到application.ini有:

[general] 
key = value 

>>> config._sections.general.key 
'value' 
+2

不錯的訣竅,但這種方法的用戶應該小心,當訪問像''config._sections.general.key =「3」''這不會改變配置選項的內部值,因此只能使用爲只讀訪問。如果在''.read()''命令之後配置被擴展或改變(爲某些部分添加選項,值對, - >其中插值可能非常重要),則不應使用此訪問方法!另外,對私有的''config._sections [「section」] [「opt」]''進行任何訪問都會繞開插值並返回原始值! – Gabriel 2015-05-06 15:06:15

2

ConfigObj是ConfigParser一個很好的選擇,它提供了更大的靈活性:

  • 嵌套的區段(小節),任何級別
  • 值列表
  • 多行值
  • 字符串插值(替代)
  • 集成了強大的驗證系統包括自動類型檢查/轉換重複部分並允許默認值
  • 當寫出配置文件,ConfigObj保留
  • 許多有用的方法和選擇工作的所有意見和成員的順序和部分使用配置文件(如 '刷新' 方法)
  • 完整的Unicode支持

它有一些抽獎背上:

  • 您不能設置分隔符,它必須是= ...(pull request
  • 你不能爲空值,那麼你可以,但他們看起來喜歡:fuabr =,而不是僅僅fubar這看起來奇怪,是錯誤的。
+1

Sardathrion是正確的,ConfigObj是如果你想保留文件中的註釋和原始文件中的部分順序的路。 ConfigParser只會清除您的意見,並會在某些時候對訂單進行爭奪。 – Arise 2016-10-11 07:20:12