将Python导入CSV列表我有一个CSV文件,有大约2000张记录。每个记录都有一个字符串,并有一个类别。This is the first line, Line1This is the second line, Line2This is the third line, Line3我需要把这个文件读成这样的列表;List = [('This is the first line', 'Line1'),
('This is the second line', 'Line2'),
('This is the third line', 'Line3')]如何导入这个csv到我需要使用Python的列表中吗?
3 回答
RISEBY
TA贡献1856条经验 获得超5个赞
csv
import csvwith 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']]
import csvwith open('test.csv', 'rb') as f: reader = csv.reader(f) your_list = map(tuple, reader)print your_list# [('This is the first line', ' Line1'),# ('This is the second line', ' Line2'), # ('This is the third line', ' Line3')]
import csvwith open('file.csv', 'r') 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']]
繁花如伊
TA贡献2012条经验 获得超12个赞
import csvwith open('file.csv', 'r') 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']]
冉冉说
TA贡献1877条经验 获得超1个赞
Python更新3:
import csvfrom pprint import pprintwith open('text.csv', newline='') as file: reader = csv.reader(file)l = list(map(tuple, reader)) pprint(l)[('This is the first line', ' Line1'),('This is the second line', ' Line2'),('This is the third line', ' Line3')]
newline=''
.
添加回答
举报
0/150
提交
取消