ConfigParser 无意中添加了额外的行和字符

ConfigParser unintentionally adding extra lines and characters

我正在尝试使用配置解析器来跟踪一些需要在程序之间传递的变量。 (我不确定这就是 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)

您正在以 r+ 模式打开文件进行写入。 The documentation for open 声明这不会截断文件。实际上,您只是覆盖了文件的一部分。

我将模式更改为 w+,多余的行不再存在。