Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将.csv导入字典_Python_Csv_Dictionary - Fatal编程技术网

Python 将.csv导入字典

Python 将.csv导入字典,python,csv,dictionary,Python,Csv,Dictionary,我正在尝试将.csv文件导入dict。 我的问题是,当我试图从dict读取时,我没有得到输出? 为什么 .csv文件如下所示: F59241,GG1212 F65563,QQ434 F59226,WW343 F69215,CC434 我试过的是FLOWING: import csv with open('myfile.csv', mode='r') as infile: reader = csv.reader(infile,) with open('mtfile.csv', mode

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

.csv文件如下所示:

F59241,GG1212
F65563,QQ434
F59226,WW343
F69215,CC434
我试过的是FLOWING:

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")
谁能告诉我我做错了什么? 谢谢

退出块时,with构造将关闭文件。您需要先用块读取
infle
中的数据

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")
退出块时,with构造将关闭文件。您需要先用块读取
infle
中的数据

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")

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

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'}

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

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'}

不要使用
if DICT.get(key):
使用
if key in DICT
,除非您确实想检查该
键的值是否为假/不存在,而不是
if DICT.get(key):
使用
if key in DICT
,除非您确实想检查该
键的值是否为false/不存在。“失踪”是我问题上的一个拼写错误。我感兴趣的是你说的关于填充物的话。我该怎么做呢?那就用Tnx吧。“失踪”是我问题上的一个拼写错误。我感兴趣的是你说的关于填充物的话。我该怎么做呢?