Python - 无法从CSV文件中读取字典值

时间:2018-04-07 22:18:28

标签: python csv

我有两种不同的CSV文件。其中一个使用双引号,另一个不使用。

A: "shipment_id","status","to_name","to_address_1" etc

B: shipment_id,status,to_name,to_address_1 etc

无论提交哪种类型的CSV,如何阅读CSV并打印shipment_id的值?

当CSV不使用双引号时,我的代码似乎不起作用。

with open(file_location) as f_obj:
    reader = csv.DictReader(f_obj, delimiter=',')
    for line in reader:
         print(line['shipment_id'])

3 个答案:

答案 0 :(得分:0)

试试这个:

with open(file_location) as f_obj:
    f_obj = f_obj.read().replace('"','').splitlines()
    reader = csv.DictReader(f_obj, delimiter=',')
    for line in reader:
         print(line['shipment_id'])
如果

.replace('"', '')有双引号,它将起作用,如果它没有,它将无效。

让我知道它是否有效:)

答案 1 :(得分:0)

根据我认为的.csv文件看起来和pandas read_csv的体验,我决定按照以下方式提供输入

  

test.csv文件的示例

"1233",No,N,C
9999,OK,C,N
  

test1.csv文件的示例

"321",ok,P,A
980,No,A,G
"1980","No",A,"G"

test.csv 指定字段名的代码,带打印(行[' shipment_id']):

import csv
with open('test.csv') as f_obj:
    reader = csv.DictReader(f_obj, delimiter=',', fieldnames=['shipment_id','status','to_name','to_address_1'])
    for line in reader:
        print(line['shipment_id'])

输出

1233
9999

test1.csv 指定字段名的代码,带打印(行[' shipment_id']):

with open('test1.csv') as f_obj:
    reader_ddQ = csv.DictReader(f_obj, delimiter=',', fieldnames=['shipment_id','status','to_name','to_address_1'])
    for line in reader_ddQ:
        print(line['shipment_id'])

输出

321
980
1980

test1.csv 指定字段名的代码,带打印(行)

with open('test1.csv') as f_obj:
    reader = csv.DictReader(f_obj, delimiter=',', fieldnames=['shipment_id','status','to_name','to_address_1'])
    for line in reader:
        print(line)

输出

OrderedDict([('shipment_id', '321'), ('status', 'ok'), ('to_name', 'P'), ('to_address_1', 'A')])
OrderedDict([('shipment_id', '980'), ('status', 'No'), ('to_name', 'A'), ('to_address_1', 'G')])
OrderedDict([('shipment_id', '1980'), ('status', 'No'), ('to_name', 'A'), ('to_address_1', 'G')])

csv.DictReader

的来源

答案 2 :(得分:0)

您应该可以使用quotechar作为参数:

reader = csv.DictReader(f_obj, delimiter=',', quotechar='"')

(或者'\"' - 我不知道Python如何处理这个问题。)

这应适用于您的两种版本的数据。

如果DictReader不支持quotechar参数,请尝试直接在csv.reader上使用它。