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 个回答
9
我不太确定你想要达到什么目的,但如果你只是想知道某些列是否在CSV文件中,并且你确定所有行都有相同的列,而你想使用字典读取器的话,可以用这个方法
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)
12
根据你的修改,你需要在逗号后面跳过最开始的空格。
这样做就可以了:
>>> reader = csv.DictReader(open(PathFile),skipinitialspace=True)