简体   繁体   English

如何读取 CSV 文件并跳过 header 行

[英]How to read a CSV file and skip the header row

I am using the following code我正在使用以下代码

import csv

with open('skill.csv', 'r') as csv_file:
    csv_reader = csv.DictReader(csv_file)

    # next(csv_reader)

    for line in csv_reader:
        print(line)

Here is what the csv contains:这是 csv 包含的内容:

Skill,amount_of_skill
First aid,50
Stealth,40

It outputs:它输出:

OrderedDict([('Skill', 'First aid'), ('amount_of_skill', '50')])
OrderedDict([('Skill', 'Stealth'), ('amount_of_skill', '40')])

How do I get it to just say:我怎么让它说:

First Aid    50
Stealth   40

You are reading as a dict but you need a simple csv.您正在阅读作为字典,但您需要一个简单的 csv。

Here is as it should be:这是应该的:

import csv
with open('skill.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    next(csv_reader) #to skip header
    for line in csv_reader:
        print('  '.join(line))

The problem with your code is that you don't access the values of the dictionary, you just print the dictionary that holds the data for each line.您的代码的问题是您不访问字典的values ,您只需打印包含每行数据的字典。

with open("skill.csv", "r") as csv_file:
    reader = csv.DictReader(csv_file, delimiter=",")
    for line in reader:
        print(" ".join(line.values()))

Output: Output:

First aid 50
Stealth 40

You could also use the unpacking operator ( * ) in the print statement:您还可以在 print 语句中使用解包运算符 ( * ):

print(*line.values())

You are reading the csv file into a dictionary.您正在将 csv 文件读入字典。

You don't need any library to read the csv.. You can just open the file and split the fields by comma:您不需要任何库来读取 csv.. 您只需打开文件并用逗号分隔字段:

with open('skill.csv', 'r') as csv_file:
    csv_reader = csv_file.readlines()


for line in csv_reader:
    print(line.replace(',', ' '))

Output: Output:

First aid 50
Stealth 40

Purely for fun... if you wanted to smash it all into one line, you could do:纯粹是为了好玩......如果你想把它全部粉碎成一行,你可以这样做:

print(*[i.replace(',', ' ') for i in open('skills.csv').readlines()[1:]], sep='')

Output: Output:

First aid 50
Stealth 40

Readable... not really.可读...不是真的。 Fun?乐趣? Yes!是的!


Something more readable:更具可读性的东西:

with open('skills.csv') as f:
    lines = f.readlines()[1:]

print(*[i.replace(',', ' ') for i in lines], sep='')

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

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