Python 如何将多行 INI 文件转换为单行 INI 文件?

How to convert multi line INI file to single line INI file in Python?

我的 INI 文件格式如下:

但我需要它看起来像这样:

编写此类转换器最简单的解决方案是什么? 我尝试在 Python 中执行此操作,但它没有按预期工作。我的代码如下。

def fix_INI_file(in_INI_filepath, out_INI_filepath):
count_lines = len(open( in_INI_filepath).readlines() )
print("Line count: " + str(count_lines))

in_INI_file = open(in_INI_filepath, 'rt')

out_arr = []
temp_arr = []
line_flag = 0
for i in range(count_lines):
    line = in_INI_file.readline()
    print (i)

    if line == '':
        break

    if (line.startswith("[") and "]" in line)   or   ("REF:" in line)    or   (line == "\n"):
        out_arr.append(line)
    else:
        temp_str = ""
        line2 = ""
        temp_str = line.strip("\n")

        wh_counter = 0
        while 1:             
            wh_counter += 1
            line = in_INI_file.readline()
            if (line.startswith("[") and "]" in line)   or   ("REF:" in line)    or   (line == "\n"):
                line2 += line
                break
            count_lines -= 1
            temp_str += line.strip("\n") + " ; "    
        temp_str += "\n"
        out_arr.append(temp_str)
        out_arr.append(line2 )


out_INI_file = open(out_INI_filepath, 'wt+')  
strr_blob = ""
for strr in out_arr:
    strr_blob += strr
out_INI_file.write(strr_blob)


out_INI_file.close()
in_INI_file.close()

幸运的是,有一种比手动解析文本更容易处理这个问题的方法。内置 configparser module supports keys without values via the allow_no_values 构造函数参数。

import configparser


read_config = configparser.ConfigParser(allow_no_value=True)
read_config.read_string('''
[First section]
s1value1
s1value2

[Second section]
s2value1
s2value2
''')

write_config = configparser.ConfigParser(allow_no_value=True)

for section_name in read_config.sections():
    write_config[section_name] = {';'.join(read_config[section_name]): None}

with open('/tmp/test.ini', 'w') as outfile:
    write_config.write(outfile)

虽然我没有立即看到使用相同的 ConfigParser 对象进行读写的方法(它保持原始键的默认值),但使用第二个对象作为写入器应该会产生你想要的结果正在寻找。

上述示例的输出:

[First section]
s1value1;s1value2

[Second section]
s2value1;s2value2