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

问题描述 投票:0回答:1

我的INI文件格式如下:

enter image description here

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

enter image description here

写这样的转换器最简单的解决方案是什么?我试图用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()
python text ini converters
1个回答
0
投票

幸运的是,比手工解析文本要容易得多。内置的configparser模块通过configparser构造函数参数支持不带值的键。

allow_no_values

虽然我没有立即看到一种使用相同的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)
© www.soinside.com 2019 - 2024. All rights reserved.