0
我正在尝试使用配置解析器来跟踪需要在程序之间传递的一些变量。 (我不确定这是ConfigParser的意思,但它是程序如何工作,所以我仍然在使用它。)ConfigParser正在做这个奇怪的事情,但是,在最后的文件会添加几行空白行,然后用文本重复前一行的最后几个字符(或者有时来自前一行的文本)。老实说,如果你只是运行下面的代码,就会更容易理解。ConfigParser无意中添加额外的行和字符
无论如何,我搜索了网页,找不到任何提到这个问题。任何想法有什么不对?我应该放弃并尝试不同的图书馆吗?
任何和所有的帮助表示赞赏,非常感谢你!
操作系统:Windows使用Python 2.7.10
代码重现错误(变化<>用户到用户):
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)
由于某种原因,昨天当我使用w +时,我留下了一个空白文件,所以我切换到r +。但是你是对的,切换到w +似乎解决了这个问题。在排除故障时,我必须更换别的东西。无论如何,非常感谢!真心赞赏! – Shmuelt