从csv文件读取数据放入字典python

时间:2016-01-16 02:59:20

标签: python python-2.7 csv dictionary

  

块引用

帮我看看我的csv文件。我有一个csv文件test8.csv,我想从该文件读取数据并放到dict,从csv文件:第一行是value dict的矩阵大小我将创建,第二行是key dict,下一行是matrix的值:

文件csv:

1,5 
OFFENSE INVOLVING CHILDREN 
95   
96
35
80
100
2,2
BATTERY,THEFT
173,209   
173,224

输出预期:

dict={['OFFENSE INVOLVING CHILDREN']: 
      [(95,), (96,), (35,), (80,), (100,)], 
      ['BATTERY', 'THEFT']:[(173, 209), (173, 224)]}

这是我的一段代码,我不想继续:

_dir = r'D:\s2\semester 3\tesis\phyton\hasil'
with open(os.path.join(_dir, 'test8.csv'), 'rb') as csv_file:
dataReader= csv.reader(csv_file, delimiter=' ', quotechar='|')

2 个答案:

答案 0 :(得分:4)

这不是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)

答案 1 :(得分:0)

CSV文件是comma-separated values文件的缩写。只需将现有的内容视为文本文件即可。

您可以先将文件读入内存:

with open('test8.csv','r') as f:
    lines = f.readlines()

然后,由于文件结构已知, 可以逐个处理。

def remove_line_comment(line,comment_char='#'):
    i = 0
    for c in line:
        if c != comment_char:
            i+=1
        else:
            break
    return line[:i]

output = dict() 

for line_number,line in enumerate(lines):
    line = remove_line_comment(line)
    line = line.strip()    # remove empty space on both sides
    line = line.split(',') # split the line with comma as the separator 

    # as indicated, I assume the first line in the file is always 
    # the indicative of the size of key and the size of value of the first diction item 
    if line_number == 0: 
        key_size, value_size = int(line[0]), int(line[1]) 
        line_number_counter = line_number 

    elif line_number == line_number_counter+1:
        # dictionary key cannot be unhashable object 
        key = line[0] if key_size == 1 else tuple(line) 
        value = []

    elif line_number >= line_number_counter+2 and line_number < line_number_counter+1+value_size: 
        value.extend[line]

    elif line_number == line_number_counter+1+value_size:
        value.extend(line)
        output[key] = value

    else:
        key_size, value_size = int(line[0]), int(line[1]) 
        line_number_counter = line_number 

这样就可以了。