Domanda

My goal is quite simple, but I couldn't find it on the guide for configobj. When I run my code I want it to write to a file but not erase what there's in the file already.

I would like everytime I run this it should write underneath what's already in the file

This is my current code: That erase/overwrite what's inside the dasd.ini already

from configobj import ConfigObj

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

Soluzione

this would be remarkably simpler if configobj accepted a file-like object instead of a file name. This is a solution i offered in comments.

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())

Altri suggerimenti

If I understand your question correctly, doing what you want is a very simple change. Use the following syntax to create your initial config object. This reads in keys and values from the existing file.

config = ConfigObj("dasd.ini")

Then you can add new settings or change the existing ones as in your example code.

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

After you write it out using config.write(), you'll find that your dasd.ini file contains the original and new keys/values merged. It also preserves any comments you had in your original ini file, with new keys/values added to the end of each section.

Check out this link, I found it to be quite helpful: An Introduction to ConfigObj

try it: You have to read all keys and values of the section if the section existed already and then write the whole section data

# -*- 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)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top