如何保存配置文件/ python文件IO

时间:2009-09-14 18:35:36

标签: python file file-io configuration-files

我有这个用于打开.cfg文件的python代码,写入并保存它:

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

这看起来是正常还是我遗漏了一些关于如何打开写保存文件的内容?是否有更标准的方式来读取和写入配置文件?

我问,因为我有两个方法似乎做同样的事情,他们得到配置文件句柄('cf')调用cf.set('blah','foo'bar)然后使用save_lock_file(cf)上面打电话。对于一种方法,它起作用,对于另一种方法,写入永远不会发生,不知道为什么在这一点上。

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

3 个答案:

答案 0 :(得分:13)

请注意,使用ConfigObj可以简化配置文件处理。

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

from configobj import ConfigObj
config = ConfigObj(filename)

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

答案 1 :(得分:1)

对我来说很好。

如果两个地方都调用get_lock_file,然后调用cf.set(...),然后调用save_lock_file,并且不会引发任何异常,则此操作应该有效。

如果您有不同的线程或进程访问同一个文件,您可能会遇到竞争条件:

  1. 线程/进程A读取文件
  2. 线程/进程B读取文件
  3. 线程/进程A更新文件
  4. 线程/进程B更新文件
  5. 现在文件只包含B的更新,而不是A的。

    另外,对于安全的文件编写,不要忘记with语句(Python 2.5及更高版本),它会为你节省一次try / finally(如果你没有使用{应该使用它) {1}})。来自with的文档:

    ConfigParser

答案 2 :(得分:1)

适合我。

C:\temp>type svn.lock
[some_prop_section]
Hello=World

C:\temp>python
ActivePython 2.6.2.2 (ActiveState Software Inc.) based on
Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 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()
...
>>> def used_like_this():
...         cf = get_lock_file()
...         cf.set('some_prop_section', 'some_prop', 'some_value')
...         save_lock_file(cf)
...
>>> used_like_this()
>>> ^Z


C:\temp>type svn.lock
[some_prop_section]
hello = World
some_prop = some_value


C:\temp>