1

我正在尝试将 .csv 文件导入字典。我的麻烦是,当我尝试从 dict 读取时,我没有得到输出?为什么??

.csv 文件如下所示:

F59241,GG1212
F65563,QQ434
F59226,WW343
F69215,CC434

我尝试过的是:

import csv

with open('myfile.csv', mode='r') as infile:
    reader = csv.reader(infile,)
with open('mtfile.csv', mode='w') as outfile:
    writer = csv.writer(outfile)
DICT = {rows[0]:rows[1] for rows in reader}
n = ['F59241', 'F65563', 'F59226', 'F69215']

for key in n:
    if DICT.get(key):
        print ((key) + ' : ' + DICT[key])
    else:
        print((key) + ' : ' + "Not Available")

谁能告诉我我做错了什么?谢谢

4

2 回答 2

6

当您退出块时, with 构造会关闭文件。您需要先读取infilewith 块中的数据

import csv

with open('myfile.csv', mode='r') as infile:
    reader = csv.reader(infile,)
    DICT = {rows[0]:rows[1] for rows in reader if len(rows) == 2}
    print DICT

n = ['F59241', 'F65563', 'F59226', 'F69215']

for key in n:
    if DICT.get(key):
        print ((key) + ' : ' + DICT[key])
    else:
        print((key) + ' : ' + "Not Available")
于 2013-06-23T12:02:12.737 回答
1

正如 Nirk 指出的那样,这些with块在退出时会关闭文件,因此当您尝试读取文件时(通过迭代reader)它会引发错误。您需要在循环中创建字典,或者将文件的内容放入内存。我的建议如下:

from csv import reader
with open('myfile.csv',mode='r') as infile:
    d = dict(reader(infile))

>>> d
{'F59226': 'WW343', 'F65563': 'QQ434', 'F59241': 'GG1212', 'F69215': 'CC434'}
于 2013-06-23T13:09:22.313 回答