我认为这对你有用:
import csv
path = 'text.csv' #change to path of your csv file
thelist = [] #define new list
with open(path, 'r') as csvfile: #open csv file
reader = csv.reader(csvfile) #read it
for row in reader: #iterate through each row
for item in row: #iterate through each item of that row
thelist.append(int(item)) #convert item to an int and add it to thelist
print(thelist) #print it
请注意,csv 文件中的所有项目都必须是整数才能正常工作,否则会引发错误。您可以将int(item) 更改为item 以获取字符串列表
文本.csv:
1,2,3,4,5,6
7,8,9,0,1,2
3,4,5,6,7,8
4,5,6,7,8,9
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 9]
奖金,可能没用,单行(没有csv 模块):
使用列表理解:
thelist = [int(item) for item in open('text.csv').read().replace('\n', ',').split(',')]
...或者,map:
thelist = list(map(int, open('text.csv').read().replace('\n', ',').split(',')))
...或者with,使用后会自动关闭文件:
with open('text.csv') as f: thelist = list(map(int, f.read().replace('\n',',').split(',')))
Run and edit these one-liners online