【问题标题】:How to convert multi line INI file to single line INI file in Python?如何在 Python 中将多行 INI 文件转换为单行 INI 文件?
【发布时间】:2020-07-17 21:54:41
【问题描述】:

我的 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()

【问题讨论】:

  • 您的示例输入似乎不是有效的 .ini 文件。但是如果你有一个典型的 .ini 文件,你应该使用 Python 的内置解析器:docs.python.org/3/library/configparser.html。这肯定会有助于读取文件,并且可能会简化您需要的任何自定义输出格式的创建。

标签: python text ini converters


【解决方案1】:

幸运的是,有一种比手动解析文本更简单的方法来处理这个问题。内置的configparser 模块通过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

【讨论】:

    猜你喜欢
    • 2016-06-05
    • 1970-01-01
    • 2013-06-23
    • 1970-01-01
    • 2011-12-26
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    相关资源
    最近更新 更多