0

我的目标很简单,但我在 configobj 指南上找不到它。当我运行我的代码时,我希望它写入文件但不删除文件中已经存在的内容。

我希望每次运行它时它都应该写在文件中已有的内容下面

这是我当前的代码:擦除/覆盖dasd.ini中的内容

from configobj import ConfigObj

config = ConfigObj()
config.filename = "dasd.ini"
#
config['hey'] = "value1"
config['test'] = "value2"
#
config['another']['them'] = "value4"
#
config.write()
4

3 回答 3

2

如果 configobj 接受类似文件的对象而不是文件名,这将非常简单。这是我在评论中提供的解决方案。

import tempfile
with tempfile.NamedTemporaryFile() as t1, tempfile.NamedTemporaryFile() as t2, open('dasd.ini', 'w') as fyle:
    config = ConfigObj()
    config.filename = t1.file.name
    config['hey'] = "value1"
    config['test'] = "value2"
    config['another']['them'] = "value4"
    config.write()
    do_your_thing_with_(t2)
    t1.seek(0)
    t2.seek(0)
    fyle.write(t2.read())
    fyle.write(t1.read())
于 2013-09-22T12:09:25.117 回答
0

如果我正确理解您的问题,那么做您想做的事情是一个非常简单的改变。使用以下语法创建初始配置对象。这会从现有文件中读取键和值。

config = ConfigObj("dasd.ini")

然后,您可以添加新设置或更改现有设置,如示例代码中所示。

config['hey'] = "value1"
config['test'] = "value2"

使用 config.write() 将其写出后,您会发现 dasd.ini 文件包含合并的原始键/值和新键/值。它还保留了您在原始 ini 文件中的所有注释,并在每个部分的末尾添加了新的键/值。

查看此链接,我发现它很有帮助:ConfigObj 简介

于 2013-10-23T02:59:15.163 回答
0

试试看:如果该部分已经存在,则必须读取该部分的所有键和值,然后写入整个部分数据

# -*- coding: cp950 -*-

import configobj
import os

#-------------------------------------------------------------------------
# _readINI(ini_file, szSection, szKey)
# read KeyValue from a ini file
# return True/False, KeyValue
#-------------------------------------------------------------------------
def _readINI(ini_file, szSection, szKey=None):
    ret = None
    keyvalue = None
    if os.path.exists(ini_file) :
        try:
            config = configobj.ConfigObj(ini_file, encoding='UTF8')
            if not szKey==None :
                keyvalue = config[szSection][szKey]
            else:
                keyvalue = config[szSection]

            ret = True
            print keyvalue
        except Exception, e :
            ret = False

    return ret, keyvalue


#-------------------------------------------------------------------------
# _writeINI(ini_file, szSection, szKey, szKeyValue):
# write key value into a ini file
# return True/False
# You have to read all keys and values of the section if the section existed already
# and then write the whole section data 
#-------------------------------------------------------------------------
def _writeINI(ini_file, szSection, szKey, szKeyValue):
    ret = False
    try:
        ret_section = _readINI(ini_file, szSection)

        if not os.path.exists(ini_file) :
            # create a new ini file with cfg header comment
            CreateNewIniFile(ini_file)

        config = configobj.ConfigObj(ini_file, encoding='UTF8')

        if ret_section[1] == None : 
            config[szSection] = {}
        else :
            config[szSection] = ret_section[1]

        config[szSection][szKey] = szKeyValue
        config.write()            

        ret = True
    except Exception, e :
        print str(e)

    return ret


#-------------------------------------------------------------------------
# CreateNewIniFile(ini_file)
# create a new ini with header comment
# return True/False
#-------------------------------------------------------------------------
def CreateNewIniFile(ini_file):
    ret = False
    try:
        if not os.path.exists(ini_file) :

            f= open(ini_file,'w+')
            f.write('########################################################\n')
            f.write('# Configuration File for Parallel Settings of Moldex3D #\n')
            f.write('# Please Do Not Modify This File                       #\n')
            f.write('########################################################\n')
            f.write('\n\n')

            f.close()
            ret = True

    except Exception, e :
        print e

    return ret



#----------------------------------------------------------------------
if __name__ == "__main__":
    path = 'D:\\settings.cfg'
    _writeINI(path, 'szSection', 'szKey', u'kdk12341 他dkdk')
    _writeINI(path, 'szSection', 'szKey-1', u'kdk123412dk')
    _writeINI(path, 'szSection', 'szKey-2', u'kfffk')
    _writeINI(path, 'szSection', 'szKey-3', u'dhhhhhhhhhhhh')
    _writeINI(path, 'szSection-333', 'ccc', u'555')
    #_writeINI(path, 'szSection-222', '', u'')
    print _readINI(path, 'szSection', 'szKey-2')
    print _readINI(path, 'szSection-222')
    #CreateNewIniFile(path)
于 2014-09-18T11:32:06.607 回答