我有一个大约有2000条记录的CSV文件。

每条记录都有一个字符串和一个类别:

This is the first line,Line1
This is the second line,Line2
This is the third line,Line3

我需要把这个文件读入一个列表,看起来像这样:

data = [('This is the first line', 'Line1'),
        ('This is the second line', 'Line2'),
        ('This is the third line', 'Line3')]

如何使用Python将此CSV导入到我需要的列表?


当前回答

您可以使用list()函数将csv阅读器对象转换为列表

import csv

with open('input.csv', newline='') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    rows = list(reader)
    print(rows)

其他回答

如果确定输入中没有逗号,而不是分隔类别,则可以逐行读取文件并在,,上进行分割,然后将结果推入List

也就是说,看起来您正在查看一个CSV文件,因此您可以考虑为它使用模块

result = []
for line in text.splitlines():
    result.append(tuple(line.split(",")))

接下来是一段代码,它使用csv模块,但使用第一行(csv表的头)将file.csv内容提取到dicts列表

import csv
def csv2dicts(filename):
  with open(filename, 'rb') as f:
    reader = csv.reader(f)
    lines = list(reader)
    if len(lines) < 2: return None
    names = lines[0]
    if len(names) < 1: return None
    dicts = []
    for values in lines[1:]:
      if len(values) != len(names): return None
      d = {}
      for i,_ in enumerate(names):
        d[names[i]] = values[i]
      dicts.append(d)
    return dicts
  return None

if __name__ == '__main__':
  your_list = csv2dicts('file.csv')
  print your_list

正如在评论中已经说过的,你可以在python中使用csv库。CSV意味着用逗号分隔的值,这似乎正是您的情况:一个标签和一个用逗号分隔的值。

作为一个类别和值类型,我宁愿使用字典类型而不是元组列表。

无论如何,在下面的代码中我展示了两种方式:d是字典,l是元组列表。

import csv

file_name = "test.txt"
try:
    csvfile = open(file_name, 'rt')
except:
    print("File not found")
csvReader = csv.reader(csvfile, delimiter=",")
d = dict()
l =  list()
for row in csvReader:
    d[row[1]] = row[0]
    l.append((row[0], row[1]))
print(d)
print(l)

使用csv模块:

import csv

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    data = list(reader)

print(data)

输出:

[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]

如果你需要元组:

import csv

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    data = [tuple(row) for row in reader]

print(data)

输出:

[('This is the first line', 'Line1'), ('This is the second line', 'Line2'), ('This is the third line', 'Line3')]

旧的Python 2答案,同样使用csv模块:

import csv
with open('file.csv', 'rb') as f:
    reader = csv.reader(f)
    your_list = list(reader)

print your_list
# [['This is the first line', 'Line1'],
#  ['This is the second line', 'Line2'],
#  ['This is the third line', 'Line3']]