【发布时间】: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