[英]How do I read CSV files and put it in list with Python?
Sorry, I'm a noob.对不起,我是菜鸟。 I have a csv file like this
我有一个像这样的 csv 文件
customerID , gender , ...
5575-GNVDE , Female , ...
9763-GRSKD , Male , ...
I want put "customerID" column in list我想把“customerID”列放在列表中
ex:前任:
print(customerID)
like喜欢
[5575-GNVDE, 9763-GRSKD , ...]
I already write the code我已经写了代码
csvFile = open("WA_Fn-UseC_-Telco-Customer-Churn.csv", "r")
reader = csv.reader(csvFile)
# create list
customerID = []
for item in reader:
# ignore first line
if reader.line_num == 1:
continue
customerID += item[0]
print(customerID)
csvFile.close()
it show like this它像这样显示
['5', '5', '7', '5', '-', 'G', 'N', 'V', 'D', 'E','9', '7', '6', '3', '-', 'G', 'R', 'S', 'K', 'D',...]
I already read:我已经读过:
Please help me.请帮我。 Thank you.
谢谢你。
You are using this:你正在使用这个:
customerID += item[0]
But that doesn't do what you think it does.但这并不像你认为的那样。
customerID
is a list and you're using the add operator on it, so Python tries to interpret item[0]
as a list as well, which is a str
, but can be considered a list of characters - so that's exactly what gets added. customerID
是一个列表,您在其上使用 add 运算符,因此 Python 也尝试将item[0]
解释为一个列表,它是一个str
,但可以被视为字符列表 - 所以这正是添加的内容.
Instead, use:相反,使用:
customerID.append(item[0])
Or, if you prefer:或者,如果您愿意:
customerID += [item[0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.