给出以下脚本:
import ConfigParser
from datetime import datetime
import time
def write_stuff():
section = "test"
item = "oh hey there"
conf_filename = "test.conf"
conf = ConfigParser.ConfigParser()
conf.readfp(open(conf_filename, 'r', 0))
timestamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
conf.set(section, timestamp, item)
with open(conf_filename, "w", 0) as conf_file:
# time.sleep(1)
conf.write(conf_file)
write_stuff()
write_stuff()
write_stuff()
write_stuff()
它只会向文件写入一个条目,如下所示:
$ touch test.conf
$ python tests.py # this is what I've named the above
$ $ cat test.conf
[test]
2012-10-10_231439 = oh hey there
但是,如果取消注释time.sleep(1),则会显示所有条目。奇怪的是(对我来说,无论如何),如果你有一次调用write_stuff(),并且从shell快速连续调用脚本,这甚至会发生。我认为一旦Python退出,无论进入磁盘的是什么都会进入磁盘。发生了什么事?
环境:Mac OS X 10.8上的Python 2.7.3
答案 0 :(得分:3)
这里的问题是您在配置文件中使用的键值是时间戳,分辨率为1秒。这意味着,当您连续四次致电write_stuff()
时,时间没有变化,时间戳不会改变,您只需覆盖之前的值,而不是添加新值
您需要做的是每次都生成一个唯一的键值。如果你想保留时间戳值,那么这将起作用:
count = 0
def write_stuff():
global count
section = "test"
item = "oh hey there"
conf_filename = "test.conf"
conf = ConfigParser.ConfigParser()
conf.readfp(open(conf_filename, 'r', 0))
timestamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")+ "_%s" % count
count += 1
conf.set(section, timestamp, item)
with open(conf_filename, "w", 0) as conf_file:
conf.write(conf_file)
请注意,写入配置文件的值不会按任何特定顺序排列。
答案 1 :(得分:2)
您正在反复编写相同的条目,使用"a"
代替"w"
来附加文件:
with open("test.txt", "a") as myfile:
myfile.write("appended text")
Mybe你想要this之类的东西,所以该部分会被打印一次,你可以添加多个项目:
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'wb') as configfile:
config.write(configfile)
输出:
[Section1]
bar = Python
baz = fun
a_bool = true
an_int = 15
foo = %(bar)s is %(baz)s!
a_float = 3.1415
如您所见,您应该在一次写入中执行此操作,而无需多次调用您的函数。