I'm attempting to use config parser to keep track of some variables that need to get passed between programs. (I'm not sure that this is what ConfigParser is meant for, but it's how the program worked when I got it, so I'm still using it.) ConfigParser is doing this weird thing, however, where at the end of the file it is adding a few blank lines and then repeating the last few characters of the immediately preceding line with text (or sometimes from the text which had been there previously). Honestly, it's easier to understand if you just run the code below.
In any event, I searched the web and couldn't find any mention of this problem. Any idea what's wrong? Should I just give up and try a different library?
Any and all help is appreciated, thank you so much!
System: Windows using Python 2.7.10
Code to reproduce the error (change < >user to your user):
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)
You are opening the file for writing with mode r+
. The documentation for open states that this does not truncate the file. In effect, you are only overwriting a part of the file.
I changed the mode to w+
and the extra lines were not there anymore.