在python中读取CSV的第一列 [英] Read in the first column of a CSV in python
本文介绍了在python中读取CSV的第一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个CSV(mylist.csv),其中有2列看起来与此类似:
I have a CSV (mylist.csv) with 2 columns that look similar to this:
jfj840398jgg item-2f
hd883hb2kjsd item-9k
jie9hgtrbu43 item-12
fjoi439jgnso item-3i
我需要将第一列读入变量,这样我才能得到:
I need to read the first column into a variable so I just get:
jfj840398jgg
hd883hb2kjsd
jie9hgtrbu43
fjoi439jgnso
我尝试了以下操作,但这只是给我每列的第一个字母:
I tried the following, but it is only giving me the first letter of each column:
import csv
list2 = []
with open("mylist.csv") as f:
for row in f:
list2.append(row[0])
所以上述代码的结果使我的list2为:
so the results of the above code are giving me list2 as:
['j','h','j','f']
['j', 'h', 'j', 'f']
推荐答案
您应split
该行,然后附加第一项
You should split
the row and then append the first item
list2 = []
with open("mylist.csv") as f:
for row in f:
list2.append(row.split()[0])
您还可以使用列表理解,这是创建列表的非常标准的方法:
You could also use a list comprehension which are pretty standard for creating lists:
with open("mylist.csv") as f:
list2 = [row.split()[0] for row in f]
这篇关于在python中读取CSV的第一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文