我想返回一个文件包含的字典。我所拥有的是这段代码:
def read_report(filename):
new_report = {}
input_filename = open(filename)
for line in input_filename:
lines = line[:-1]
new_report.append(lines)
input_filename.close()
return new_report
它说我不能附加到字典。那么我如何将文件中的行添加到字典中呢?假设我的文件名是这样的:
shorts: a, b, c, d
longs: a, b, c, d
mosts: a
count: 11
avglen: 1.0
a 5
b 3
c 2
d 1
答案 0 :(得分:0)
如果您重写输入文件以使第一行和第二行具有统一的行,您可以尝试这样做:
编辑:修改代码以支持带空格分隔符的行而不是冒号(:)
def read_report(filename):
new_report = {}
f = open(filename)
for line in f:
if line.count(':') == 1:
key, value = line.split(':')
else:
key, value = line.split(' ')
new_report[key] = value.split(',')
f.close()
return new_report
答案 1 :(得分:0)
我假设您的文件的最后几行(不包含:
的那些行)将被忽略。
from collections import defaultdict
d = defaultdict(list)
with open('somefile.txt') as f:
for line in f:
if ':' in line:
key, val = line.split(':')
d[key.strip()] += val.rstrip().split(',')
答案 2 :(得分:0)
def read_line(filename):
list = []
new_report = {}
file_name = open(filename)
for i in file_name:
list.append(i[:-1])
for i in range(len(list)):
new_report[i] = list[i]
file_name.close()
return new_report