如何保存配置文件/ python文件IO [英] How to save a configuration file / python file IO

查看:120
本文介绍了如何保存配置文件/ python文件IO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下python代码可打开.cfg文件,对其进行写入并保存:

I have this python code for opening a .cfg file, writing to it and saving it:

import ConfigParser 

    def get_lock_file():
        cf = ConfigParser.ConfigParser()
        cf.read("svn.lock")
        return cf
    def save_lock_file(configurationParser):
        cf = configurationParser
        config_file = open('svn.lock', 'w')
        cf.write(config_file)
        config_file.close()

这是正常现象还是我缺少有关如何打开-写入-保存文件的信息?有没有更标准的读写配置文件的方法?

Does this seem normal or am I missing something about how to open-write-save files? Is there a more standard way to read and write config files?

我问是因为我有两个似乎做同样事情的方法,它们得到了配置文件句柄(cf)调用cf.set('blah', foo栏),然后使用上面的save_lock_file(cf)调用。对于一种方法,它有效,而对于另一种方法,则永远不会进行写入,不确定为什么要这样做。

I ask because I have two methods that seem to do the same thing, they get the config file handle ('cf') call cf.set('blah', 'foo' bar) then use the save_lock_file(cf) call above. For one method it works and for the other method the write never takes place, unsure why at this point.

def used_like_this():
        cf = get_lock_file()
        cf.set('some_prop_section', 'some_prop', 'some_value')
        save_lock_file(cf)


推荐答案

请注意,使用ConfigObj,配置文件的处理更为简单。

Just to note that configuration file handling is simpler with ConfigObj.

要读取然后写入配置文件:

To read and then write a config file:

from configobj import ConfigObj
config = ConfigObj(filename)

value = config['entry']
config['entry'] = newvalue
config.write()

这篇关于如何保存配置文件/ python文件IO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆