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

2024-10-01 13:44:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python代码来打开一个.cfg文件,写入并保存它:

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

这看起来正常吗?还是我缺少了一些关于如何打开写保存文件的内容?有没有更标准的方法来读写配置文件?在

我之所以这么问,是因为我有两个方法似乎在做同样的事情,它们得到了config file handle('cf')调用cf.set公司('blah','foo'bar)然后使用上面的save\u lock_file(cf)调用。对于一个方法,它是有效的,而对于另一个方法,写永远不会发生,不知道为什么在这一点上。在

^{pr2}$

Tags: 文件方法代码importconfiglockgetsave
3条回答

我觉得不错。在

如果两个位置都调用get_lock_file,然后是cf.set(...),然后是save_lock_file,并且没有引发异常,这应该可以工作。在

如果有不同的线程或进程访问同一文件,则可能存在争用条件:

  1. 线程/进程A读取文件
  2. 线程/进程B读取文件
  3. 线程/进程A更新文件
  4. 线程/进程B更新文件

现在文件只包含B的更新,而不是A的更新

另外,为了安全地编写文件,不要忘记with语句(Python2.5及更高版本),它将为您节省一个try/finally(如果不使用with,则应该使用该语句)。来自ConfigParser的文档:

with open('example.cfg', 'wb') as configfile:
  config.write(configfile)

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

要读取并写入配置文件:

from configobj import ConfigObj
config = ConfigObj(filename)

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

对我有用。在

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>

相关问题 更多 >