[英]Configparser set with no section
有沒有辦法讓python中的configparser 設置一個值而不在配置文件中有部分?
如果沒有,請告訴我任何替代方案。
謝謝。
更多信息:所以基本上我有一個格式的配置文件: Name: value
這是一個系統文件,我想更改給定名稱的值。 我想知道是否可以使用模塊輕松完成此操作,而不是手動編寫解析器。
您可以使用csv
模塊完成解析文件的大部分工作,並在進行更改后將其寫回 - 因此它應該相對容易使用。 我從一個答案中得到了一個想法,題目是使用Python的ConfigParser來讀取沒有部分名稱的文件 。
然而,我進行了一些更改,包括將其編碼為在Python 2和3中工作,對鍵/值分隔符進行解密,因此它幾乎可以是任何東西(但默認為冒號),以及幾個優化。
from __future__ import print_function # only for module main() test function
import csv
import sys
PY3 = sys.version_info[0] > 2
def read_properties(filename, delimiter=':'):
''' Reads a given properties file with each line of the format key=value.
Returns a dictionary containing the pairs.
filename -- the name of the file to be read
'''
open_kwargs = {'mode': 'r', 'newline': ''} if PY3 else {'mode': 'rb'}
with open(filename, **open_kwargs) as csvfile:
reader = csv.reader(csvfile, delimiter=delimiter, escapechar='\\',
quoting=csv.QUOTE_NONE)
return {row[0]: row[1] for row in reader}
def write_properties(filename, dictionary, delimiter=':'):
''' Writes the provided dictionary in key sorted order to a properties
file with each line in the format: key<delimiter>value
filename -- the name of the file to be written
dictionary -- a dictionary containing the key/value pairs.
'''
open_kwargs = {'mode': 'w', 'newline': ''} if PY3 else {'mode': 'wb'}
with open(filename, **open_kwargs) as csvfile:
writer = csv.writer(csvfile, delimiter=delimiter, escapechar='\\',
quoting=csv.QUOTE_NONE)
writer.writerows(sorted(dictionary.items()))
def main():
data = {
'Answer': '6*7=42',
'Knights': 'Ni!',
'Spam': 'Eggs',
}
filename='test.properties'
write_properties(filename, data)
newdata = read_properties(filename)
print('Read in: ')
print(newdata)
print()
with open(filename, 'rb') as propfile:
contents = propfile.read()
print('File contents: (%d bytes)' % len(contents))
print(repr(contents))
print(['Failure!', 'Success!'][data == newdata])
if __name__ == '__main__':
main()
我知道無法用configparser做到這一點,這是非常面向部分的。
另一種方法是使用Michael Foord命名為ConfigObj的Voidspace Python模塊。 在他撰寫的題為“ ConfigObj簡介 ”的文章的ConfigObj部分中,它說:
ConfigObj的最大優點是簡單。 即使對於需要幾個鍵值對的簡單配置文件,ConfigParser也要求它們位於“部分”內。 ConfigObj沒有這個限制 ,並且已經將配置文件讀入內存,訪問成員非常容易。
強調我的。
我個人喜歡將配置文件作為XML。 一個示例(取自ConfigObj文章以進行比較)您可以創建一個名為config.xml的文件,其中包含以下內容:
<?xml version="1.0"?>
<config>
<name>Michael Foord</name>
<dob>12th August 1974</dob>
<nationality>English</nationality>
</config>
在Python中,您可以獲得這樣的值:
>>> import xml.etree.cElementTree as etree
>>> config = etree.parse("config.xml")
>>> config.find("name").text
'Michael Foord'
>>> config.find("name").text = "Jim Beam"
>>> config.write("config.xml")
現在,如果我們查看config.xml,我們會看到:
<config>
<name>Jim Beam</name>
<dob>12th August 1974</dob>
<nationality>English</nationality>
</config>
優點與一般XML的優點相同 - 它是人類可讀的,在您可以想象的幾乎所有編程語言中都存在許多不錯的解析器,並且它支持分組和屬性。 當您的配置文件變大時,您還可以使用XML驗證(使用模式)在運行時之前查找錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.