Skip to main content
 首页 » 编程设计

python之在 python 中读取 .csv 的特定行数

2025年05月04日33pander-it

我有一个 csv 文件,我试图将其读入 python,然后我想将前两列存储在一个名为 name 和 gender 的变量中。我当前使用的代码如下:

import csv 
infile = open('blue.csv', 'r') 
csvfile = csv.reader(infile) 
 
name = [] 
gender = [] 
 
for row in csvfile: 
    name.append(row[0]) 
    gender.append(row[1]) 

我遇到了两个问题:

1) csv 文件有标题,所以我不希望在存储列时将它们包含在变量中

2) 我缺少 csv 文件最后一行的性别,因此我不想在将 csv 文件存储在变量中时包含它的最后一行。

我是一名 R 程序员,所以对我来说,解决这个问题的方法是读入不包括第一行和最后一行的文件,但我不确定如何在python,或者更好,如果有更好/更智能的选择。

如果有帮助,下面是模拟数据集的样子:

Name, Gender 
Bob, Male 
Susan, Female 
Doug, 

请您参考如下方法:

你写的

I am an R programmer and so to me, the way I would get around this is to read in the file excluding the first row and last row but I am unsure of how to do this in python

这可以通过 readlines 来完成和 list slicing像这样:

open('foo.csv').readlines()[1: -1] 

此外,请注意 csv.reader接受一个文件对象和一个列表:

csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called — file objects and list objects are both suitable.

所以你可以使用:

for l in csv.reader(open('foo.csv').readlines()[1: -1]): 
    ...