那不是一个csv文件,csv模块帮不了你。在csv文件中,每一行都有相等数量的列字段,这些字段由逗号等已知字符分隔。您需要为这些数据编写自己的解析器。在
这个脚本将建立字典(除了它使用一个元组作为键,因为列表不起作用…)# todo: write a testfile so the example works
open("testfile.txt", "w"). write("""1,5 # matriks size
OFFENSE INVOLVING CHILDREN # key for dictionary
95 # list of value
96
35
80
100
2,2
BATTERY,THEFT
173,209 # list of tuple value
173,224""")
def strip_comment(line):
return line.split('#', 1)[0].rstrip()
mydict = {}
with open("testfile.txt") as testfile:
for line in testfile:
# first line is the next record "matrix size"
columns, rows = (int(x) for x in strip_comment(line).split(','))
# next line is the header for this record
key = tuple(strip_comment(next(testfile)).split(','))
# the next lines are the rows for this record
vals = [tuple(int(x) for x in strip_comment(next(testfile)).split(','))
for _ in range(rows)]
mydict[key] = vals
print(mydict)