[英]How to convert multi line INI file to single line INI file in Python?
I have INI file formatted like this:我的 INI 文件格式如下:
But i need it to look like this:但我需要它看起来像这样:
What would be the easiest solution to write such converter?编写这样的转换器最简单的解决方案是什么? I tried to do it in Python, but it don't work as expected.
我试图在 Python 中这样做,但它没有按预期工作。 My code is below.
我的代码如下。
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()
Fortunately, there's a much easier way to handle this than by parsing the text by hand.幸运的是,有一种比手动解析文本更简单的方法来处理这个问题。 The built-in
configparser
module supports keys without values via the allow_no_values
constructor argument.内置的
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)
While I don't immediately see a way to use the same ConfigParser
object for reading and writing (it maintains default values for the original keys), using the second object as a writer should yield what you're looking for.虽然我没有立即看到使用相同的
ConfigParser
object 进行读取和写入的方法(它维护原始键的默认值),但使用第二个 object 作为编写器应该会产生您正在寻找的东西。
Output from the above example:上例中的 Output :
[First section]
s1value1;s1value2
[Second section]
s2value1;s2value2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.