我试图使用配置解析器来跟踪需要在程序之间传递的一些变量。 (我不确定这是ConfigParser的用途,但是当我得到它时程序是如何工作的,所以我还在使用它。)ConfigParser正在做这个奇怪的事情,但是,在文件末尾添加一些空白行,然后用文本重复前一行的最后几个字符(或者有时从之前的文本中重复)。老实说,如果你只是运行下面的代码,它会更容易理解。
无论如何,我在网上搜索过,无法找到这个问题。知道什么是错的吗?我应该放弃并尝试不同的图书馆吗?
非常感谢所有的帮助,非常感谢你!
系统:使用Python 2.7.10的Windows
重现错误的代码(将<>用户更改为您的用户):
from ConfigParser import ConfigParser
import os
def create_batch_file(name, config_dir, platform, ABCD, batch_ID, speed, parallel, turbo=False):
## setup batch_info.ini
batch_ini = os.path.join(config_dir, "batch_info.ini")
# Cast to string in case they are none object
batch_ID = str(batch_ID).lower()
parallel = str(parallel).lower()
if parallel == "none":
parallel = 1
batch_ini_contents = ["[Machine]\n",
"name = {}\n".format(name),
"platform = {}\n".format(platform),
"\n",
"[Environment]\n",
"turbo = {}\n".format(turbo),
"speed = {}\n".format(speed),
"\n",
"[Batch]\n",
"batch_id = {}\n".format(batch_ID),
"ABCD = {}\n".format(ABCD),
"parallel = {}\n".format(parallel),
"rerun = False\n",
"\n"
"[Reservation]\n"
"reserved = False\n"
"purpose = None"
]
with open(batch_ini, 'w+') as f:
f.writelines(batch_ini_contents)
return batch_ini
def temp_getter(config_dir):
config = config_dir
fl = ConfigParser()
fl.read(config)
return fl
config_dir = "C:\\Users\\<user>\\Desktop"
batch_ini = os.path.join(config_dir, "batch_info.ini")
name = "m"
platform = "p"
turbo = False
speed = "default"
batch_ID = 5
ABCD = 'abcd'
parallel = 1
purpose = "hello hello hello"
create_batch_file(config_dir=config_dir, ABCD=ABCD, turbo=turbo,
batch_ID=batch_ID, parallel=parallel, speed=speed, name=name,
platform=platform)
f = temp_getter(batch_ini)
f.set('Reservation', 'reserved', 'True')
f.set('Reservation', 'purpose', purpose)
with open(batch_ini, 'r+') as conf:
f.write(conf)
f = temp_getter(batch_ini)
f.set('Reservation', 'reserved', 'False')
f.set('Reservation', 'purpose', 'None')
with open(batch_ini, 'r+') as conf:
f.write(conf)
答案 0 :(得分:0)
您正在使用模式r+
打开文件。 The documentation for open声明这不会截断文件。实际上,您只是覆盖了文件的一部分。
我将模式更改为w+
,而且额外的行不再存在了。