【问题标题】:How to extract words from CSV file and store to list in Python如何从 CSV 文件中提取单词并存储到 Python 中的列表
【发布时间】:2013-09-27 09:30:54
【问题描述】:
outputDatafile = open('D:\\Files\\input.csv', 'r')
outputReader = csv.reader(outputDatafile, delimiter=',', quoting=csv.QUOTE_NONE)

print "OutputReader data type:",type(outputReader)
inputData= []
//i want to extract all values in csv to array
for row in outputReader:
    inputData.append(row)

我有一个 CSV 文件如下:

name1,value11,value12,value13

name2,value21,value22,value23,value24

名字3

我想提取并存储所有要列出的项目 例如:

list[0]=name1
list[1]=value11
list[2]=value12
.
.
.
.
list[5]=name2
list[6]=value21

【问题讨论】:

    标签: python csv python-2.7 python-3.x


    【解决方案1】:

    使用extend(),而不是append()。后者将每个列表作为一个元素添加到外部列表中,前者连接列表。你也可以使用+=

    with open(r'D:\Files\input.csv') as f:
        input_data = []
        for row in csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE):
            input_data += row
    

    【讨论】:

      【解决方案2】:

      .csv 可以被视为带有分隔符 ',' 的普通 txt 文档。所以您唯一需要做的就是将字符串拆分为:

      outputDatafile = open('D:\\Files\\input.csv', 'r')
      
      inputData= []
      for rows in outputDatafile:
          row = rows.rstrip().spilt(',')     #row is a list of strings splited by ',' of rows.
                                             #and row[0] is name1 and so on
      

      【讨论】:

        猜你喜欢
        • 2016-05-15
        • 1970-01-01
        • 1970-01-01
        • 2016-05-10
        • 2021-08-10
        • 1970-01-01
        • 2019-11-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多