简体   繁体   English

Python:读取 CSV 文件时缺少第一行

[英]Python: Missing first line when reading a CSV file

I am trying to test the data in a CSV file.我正在尝试测试 CSV 文件中的数据。 First I used the CSV library to put the contents of a CSV file into a dictionary:首先,我使用 CSV 库将 CSV 文件的内容放入字典中:

#CSV is the CSV file
csvfile = open(CSV)
CSVCont = csv.DictReader(csvfile)

I did a few tests without messing with the dictionary and I wanted to print out the contents.我做了一些测试而没有弄乱字典,我想打印出内容。 I used this code:我使用了这段代码:

for row in CSVCont:
    print(row)

The output I got was missing the first line of data.我得到的 output 缺少第一行数据。 My guess is the file was read wrong.我的猜测是文件读错了。 Can someone please help me with this?有人可以帮我吗?

By default, csv.DictReader consumes the first line and uses it as the header row, used as the keys in the dictionaries that represent the rows.默认情况下, csv.DictReader使用第一行并将其用作 header 行,用作表示行的字典中的键。

If your first row should not be treated as the header row, you should provide the fieldnames argument as a list of headers.如果您的第一行不应被视为 header 行,则应提供fieldnames参数作为标题列表。

If you'd rather not use headers at all, just use csv.reader instead (which will emit each row as a tuple instead of a dictionary).如果您根本不想使用标题,只需使用csv.reader代替(它将每行作为元组而不是字典发出)。

For example, with this file:例如,使用此文件:

a,b,c
d,e,f
g,h,i

Note the difference:注意区别:

with open('test.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)

outputs输出

OrderedDict([('a', 'd'), ('b', 'e'), ('c', 'f')])
OrderedDict([('a', 'g'), ('b', 'h'), ('c', 'i')])

While尽管

with open('test.csv') as f:
    reader = csv.DictReader(f, fieldnames=['1', '2', '3'])
    for row in reader:
        print(row)

outputs输出

OrderedDict([('1', 'a'), ('2', 'b'), ('3', 'c')])
OrderedDict([('1', 'd'), ('2', 'e'), ('3', 'f')])
OrderedDict([('1', 'g'), ('2', 'h'), ('3', 'i')])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM