Murphy
Murphy

Reputation: 556

Python csv.DictReader does not split at comma's

A row in my csv file:

console_ip,spsstatus,spsversion

172.19.126.182,Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x4 rsp=0x83): Unknown (0x83)^M,Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x1 rsp=0x83): Unknown (0x83)

I am getting:

{'console_ip': '172.19.126.182', 'spsversion': None, 'spsstatus': 'Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x4 rsp=0x83): Unknown (0x83)'} {'console_ip': '', 'spsversion': None, 'spsstatus': 'Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x1 rsp=0x83): Unknown (0x83)'}

Expected just one element in a dictionary:

{'console_ip': '172.19.126.182', 'spsversion': 'Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x4 rsp=0x83): Unknown (0x83)','spsstatus': 'Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x1 rsp=0x83): Unknown (0x83)'}

My code:

f = 'consolespsdata/hostIpmi_bom52'
with open(f, 'rU') as csv_file:
    csv_reader = csv.DictReader(csv_file,delimiter=",")
    for line in csv_reader:
    if line['console_ip'] is not None:
        print line

Im wondering what might be causing this issue.

Upvotes: 0

Views: 554

Answers (1)

kgf3JfUtW
kgf3JfUtW

Reputation: 14928

I get something different from what you see.


a.csv

console_ip,spsstatus,spsversion

172.19.126.182,Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x4 rsp=0x83): Unknown (0x83)^M,Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x1 rsp=0x83): Unknown (0x83)

b.py

import csv
f = 'a.csv'
with open(f, 'rU') as csv_file:
    csv_reader = csv.DictReader(csv_file,delimiter=",")
    for line in csv_reader:
        if line['console_ip'] is not None:
            print line

python b.py

{'console_ip': '172.19.126.182', 
 'spsversion': 'Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x1 rsp=0x83): Unknown (0x83)', 
 'spsstatus': 'Unable to send RAW command (channel=0x6 netfn=0x6 lun=0x0 cmd=0x4 rsp=0x83): Unknown (0x83)^M'
}

A more succinct example.

a.csv

k1,k2,k3

val1,val2,val3
val4,val5,val6

b.py

import csv
f = 'a.csv'
with open(f, 'rU') as csv_file:
    csv_reader = csv.DictReader(csv_file,delimiter=",")
    for line in csv_reader:
        if line['k1'] is not None:
            print line

python b.py

{'k3': 'val3', 'k2': 'val2', 'k1': 'val1'}
{'k3': 'val6', 'k2': 'val5', 'k1': 'val4'}

Which seems to work fine. If the second example works for you, maybe special characters in your csv files are causing issues.

Upvotes: 1

Related Questions