跳过行,csv.DictReader [英] Skipping lines, csv.DictReader

查看:113
本文介绍了跳过行,csv.DictReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标头带有讨厌的前言的文件.所以看起来像这样:

I have a file that has an obnoxious preface to the header. So it looks like this:

Review performed by:    

Meeting:    

Person:     

Number:     

Code: 



Confirmation    

Tab Separated Header Names That I Want To Use

我想跳过所有内容,并使用制表符sep标题名称作为我的代码.这是我到目前为止的内容:

I want to skip past everything and use the tab sep header names for my code. This is what I have so far:

reader = csv.DictReader(CSVFile)
for i in range(14): #trying to skip the first 14 rows
    reader.next()
for row in reader:
    print(row)
    if args.nextCode:
        tab = (row["Tab"])
        sep = int((row["Separated"]))

此代码收到此错误:

File "/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 104, in next
    row = self.reader.next()
StopIteration

我尝试打印行,以查看我在文件中的位置,然后将"range(14)"更改为范围5,但是当我打印行时,我得到了:

I tried to print the rows, to see where I was in the file, and I changed the "range(14)" to range 5, but when I print the row, I get this:

{'Review performed by:': 'Tab/tSeparated/tHeader/tNames/tThat/tI/tWant/tTo/tUse'}
Traceback (most recent call last):
  File "program.py", line 396, in <module>
    main()
  File "program.py", line 234, in main
    tab = (row["Tab"])
KeyError: 'Tab'

因此,我不太确定跳过这些顶行的正确方法.任何帮助,将不胜感激.

So I am not really sure the right way to skip those top lines. Any help would be appreciated.

推荐答案

csv.DictReader在实例化文件 时从文件中读取第一行,以获取后续行的标题.因此,它使用Review performed by:作为标题行,然后则跳过接下来的14行.

A csv.DictReader reads the first line from the file when it's instantiated, to get the headers for subsequent rows. Therefore it uses Review performed by: as the header row, then you skip the next 14 rows.

相反,在创建DictReader之前跳过之前的行:

Instead, skip the rows before creating the DictReader:

for i in range(14):
    CSVFile.next()
reader = csv.DictReader(CSVFile)
...

这篇关于跳过行,csv.DictReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆