示例文件的内容如下所示:
product: osName
customers: verizon
category: software
class: CL1
file_location: /opt/test.txt
Remarks: This is multi line data. This Line - 1 of remarks field.
This Line - 2 of remarks field.
This Line - 3 of remarks field.
我从文件读取并填充python字典的代码如下所示:
with open(txt_file) as f: for l in f: key_value = l.strip().split(':',1) txtdict[key_value[0].strip()] = key_value[1].strip()
上述解决方案只要键及其值仅在一行中,就可以正常工作。想知道如何为给定键填充可以支持多行值的python字典对象?
csv.reader
模块准确且经过特定检查:import csv
with open('test.txt') as f:
reader = csv.reader(f, delimiter=':', skipinitialspace=True)
res = {}
prev_key = ''
for row in reader:
if len(row) == 2:
k, v = row
res[k] = v
prev_key = k
else:
res[prev_key] += f'\n{row[0]}'
print(res)
输出:
{'Remarks': 'Line one\nLine 2 \nLine 3 of Remarks.', 'category': 'software', 'class': 'CL1', 'customers': 'verizon', 'file_location': '/opt/test.txt', 'product': 'osName'}
with open(txt_file) as f:
for l in f:
key_value = l.strip().split(':',1)
if len(key_value) > 1:
txtdict[key_value[0].strip()] = key_value[1].strip()
else:
txtdict[key_value[0].strip()] = None