如何保存配置文件/ python文件IO
-
07-07-2019 - |
题
我有这个用于打开.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)
解决方案
请注意,使用ConfigObj可以简化配置文件处理。
要读取然后编写配置文件:
from configobj import ConfigObj
config = ConfigObj(filename)
value = config['entry']
config['entry'] = newvalue
config.write()
其他提示
对我来说很好。
如果两个地方都调用 get_lock_file
,那么 cf.set(...)
,然后 save_lock_file
,并且不会引发异常,这应该有效。
如果您有不同的线程或进程访问同一个文件,您可能会遇到竞争条件:
- 线程/进程A读取文件
- 线程/进程B读取文件
- 线程/进程A更新文件
- 线程/进程B更新文件 醇>
现在文件只包含B的更新,而不是A的。
另外,对于安全的文件编写,不要忘记 with
语句(Python 2.5及更高版本),它会为你节省一次try / finally(如果你是的话,你应该使用它)不使用和
)。来自 ConfigParser
的文档:
with open('example.cfg', 'wb') as configfile:
config.write(configfile)
适合我。
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>
不隶属于 StackOverflow