如何保存配置文件/python文件IO
我有这个 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()
这看起来正常还是我缺少有关如何打开-写入-保存文件的信息?有没有更标准的方式来读取和写入配置文件?
我问是因为我有两个方法似乎做同样的事情,它们获取配置文件句柄('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)
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?
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请注意,使用 ConfigObj 处理配置文件更简单。
读取并写入配置文件:
Just to note that configuration file handling is simpler with ConfigObj.
To read and then write a config file:
我觉得不错。
如果两个地方都调用
get_lock_file
,然后调用cf.set(...)
,然后调用save_lock_file
,并且没有引发异常,那么这应该可以工作。如果您有不同的线程或进程访问同一文件,则可能会出现竞争条件:
现在仅文件包含 B 的更新,而不是 A 的更新。
另外,为了安全地写入文件,不要忘记
with
语句(Python 2.5 及更高版本),它会为您节省一次 try/finally (如果您不使用 <代码>与)。来自 ConfigParser 的文档:Looks good to me.
If both places call
get_lock_file
, thencf.set(...)
, and thensave_lock_file
, and no exceptions are raised, this should work.If you have different threads or processes accessing the same file you could have a race condition:
Now the file only contains B's updates, not A's.
Also, for safe file writing, don't forget the
with
statement (Python 2.5 and up), it'll save you a try/finally (which you should be using if you're not usingwith
). FromConfigParser
's docs:对我有用。
Works for me.