簡體   English   中英

如何讀取 CSV 文件並將其與 Python 一起放入列表中?

[英]How do I read CSV files and put it in list with Python?

對不起,我是菜鳥。 我有一個像這樣的 csv 文件

customerID , gender , ...
5575-GNVDE , Female , ...
9763-GRSKD , Male   , ...

我想把“customerID”列放在列表中

前任:

print(customerID)

喜歡

[5575-GNVDE, 9763-GRSKD , ...]

我已經寫了代碼

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()

它像這樣顯示

['5', '5', '7', '5', '-', 'G', 'N', 'V', 'D', 'E','9', '7', '6', '3', '-', 'G', 'R', 'S', 'K', 'D',...]

我已經讀過:

請幫我。 謝謝你。

你正在使用這個:

    customerID += item[0]

但這並不像你認為的那樣。 customerID是一個列表,您在其上使用 add 運算符,因此 Python 也嘗試將item[0]解釋為一個列表,它是一個str ,但可以被視為字符列表 - 所以這正是添加的內容.

相反,使用:

    customerID.append(item[0])

或者,如果您願意:

    customerID += [item[0]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM