python csv头文件

时间:2009-11-17 03:59:56

标签: python csv

我有一组csv标题,我试图与上传匹配。它并没有真正起作用。并非所有标头都是必需的 - 我只需要匹配文件中的内容。

reader = csv.DictReader(open(PathFile))
headers = reader.fieldnames
for header in sorted(set(headers)):
     if (header == 'ip') or (header == 'IP'):
         print  "IP found in Header"

在这种情况下,找不到IP。

for row in reader:
     if row.get('IP'):
         print  "IP found in Row"

再也找不到了。我在这个网站上搜索过 - 有:

IP = row.get('IP', None)

这也不起作用。

这是我用于测试的文件:

Email, IP, Name, City, State, zip, country, garbage
ghfddgf@gfgs.com, 34.4.34.34,Mr GH, chicago, il ,60601, us,erw ewr 
5t4g@fdsf.com, 34.45.23.34, Mr 5t,NY,NY,10101, us, er

2 个答案:

答案 0 :(得分:12)

根据您的修改,您需要在逗号后加skip the initial space

这应该这样做:

>>> reader = csv.DictReader(open(PathFile),skipinitialspace=True)

答案 1 :(得分:7)

我不确定你想要实现什么,但如果你只是想知道某些列是否为CSV,并且你确定所有行都有相同的列,并且你想使用dict reader使用这个

s="""col1,col2,col3
ok,ok,ok
hmm,hmm,hmm
cool,cool,cool"""

import csv

reader = csv.DictReader(s.split("\n"))
print reader.fieldnames
for row in reader:
    for colName in ['col3', 'col4']:
        print "found %s %s"%(colName, colName in row)
    break

输出

found col3 True
found col4 False

或类似的东西也会起作用

reader = csv.reader(s.split("\n"))
columns = reader.next()
for colName in ['col3', 'col4']:
    print "found %s %s"%(colName, colName in columns)
相关问题