Python csv.DictReader不会以逗号分隔

时间:2017-10-24 03:02:25

标签: python python-2.7

我的csv文件中的一行:

  

console_ip,spsstatus,spsversion

     

172.19.126.182,无法发送RAW命令(通道= 0x6 netfn = 0x6 lun = 0x0 cmd = 0x4 rsp = 0x83):未知(0x83)^ M,无法发送RAW命令(通道= 0x6 netfn = 0x6 lun = 0x0 cmd = 0x1 rsp = 0x83):未知(0x83)

我得到了:

  

{'console_ip':'172.19.126.182','spsversion':无,'spsstatus':'无法发送RAW命令(通道= 0x6 netfn = 0x6 lun = 0x0 cmd = 0x4 rsp = 0x83):未知( 0×83)“}   {'console_ip':'','spsversion':无,'spsstatus':'无法发送RAW命令(通道= 0x6 netfn = 0x6 lun = 0x0 cmd = 0x1 rsp = 0x83):未知(0x83)'}

预计字典中只有一个元素:

  

{'console_ip':'172.19.126.182','spsversion':'无法发送RAW命令(通道= 0x6 netfn = 0x6 lun = 0x0 cmd = 0x4 rsp = 0x83):未知(0x83)','spsstatus ':'无法发送RAW命令(通道= 0x6 netfn = 0x6 lun = 0x0 cmd = 0x1 rsp = 0x83):未知(0x83)'}

我的代码:

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

我想知道可能导致这个问题的原因。

1 个答案:

答案 0 :(得分:1)

我得到的东西与你看到的不同。

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

这似乎工作得很好。如果第二个示例适合您,则csv文件中的特殊字符可能会导致问题。