我有一个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}$
我觉得不错。在
如果两个位置都调用
get_lock_file
,然后是cf.set(...)
,然后是save_lock_file
,并且没有引发异常,这应该可以工作。在如果有不同的线程或进程访问同一文件,则可能存在争用条件:
现在文件只包含B的更新,而不是A的更新
另外,为了安全地编写文件,不要忘记
with
语句(Python2.5及更高版本),它将为您节省一个try/finally(如果不使用with
,则应该使用该语句)。来自ConfigParser
的文档:请注意,使用ConfigObj处理配置文件更简单。在
要读取并写入配置文件:
对我有用。在
相关问题 更多 >
编程相关推荐