【问题标题】:CSV IO python: converting a csv file into a list of listsCSV IO python:将csv文件转换为列表列表
【发布时间】:2016-01-15 03:36:36
【问题描述】:

如何将 csv 文件转换为列表列表,其中每行是更大列表中的条目列表?

我遇到了这个问题,因为我的一些条目中有逗号

类似的文件:

'1','2','3'  
'1,1','2,2','3,3'  

变成:

[['1','2','3']['1','1','2','2','3','3']]

代替:

[['1','2','3']['1,1','2,2','3,3']

【问题讨论】:

  • 你目前在做什么?使用图书馆,卢克...
  • 不使用csv?
  • 对不起,如果我遇到的是 python/编码新手,但什么是库?目前我只使用 csv 文件
  • @Jack:你是搜索新手吗? docs.python.org/2/library

标签: python csv


【解决方案1】:
in your data '2,2' is one string. But csv reader can deal with this:
import csv
result = []
with open("data", 'r') as f:
        r = csv.reader(f, delimiter=',')
        # next(r, None)  # skip the headers
        for row in r:
            result.append(row)

print(result)

[["'1'", "'2'", "'3'"], ["'1", "1'", "'2", "2'", "'3", '3']]

【讨论】:

  • 谢谢!!你的代码对我有用,不知道 csv.reader 函数甚至存在!感谢您的快速答复
  • @Jack,很高兴为您提供帮助。对于 csv 文件,您需要导入 csv。我现在会更新我的答案。
  • @Jack 如果我注释掉 import csv 我在 python 3.5 NameError: name 'csv' is not defined 中得到这个错误