【问题标题】:python csv headerspython csv标头
【发布时间】:2009-11-17 03:59:55
【问题描述】:

我有一组 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

【问题讨论】:

    标签: python csv


    【解决方案1】:

    根据您的编辑,您需要在逗号后添加skip the initial space。

    应该这样做:

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

    【讨论】:

      【解决方案2】:

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

      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)
      

      【讨论】:

      • 那也没用。我用我正在尝试处理的文件数据编辑了我的帖子。尝试查看标头中是否有 IP。
      • as Adam Bernier,说问题出在空格上
      猜你喜欢
      • 2015-12-08
      • 2014-04-06
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 2019-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多