为了账号安全,请及时绑定邮箱和手机立即绑定

如何将Python导入CSV列表

如何将Python导入CSV列表

白板的微信 2019-10-16 14:09:46
将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 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

使用csv模块(Python2.x):

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')]

Python3.x版本(下面@seokhoonlee)

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']]



查看完整回答
反对 回复 2019-10-17
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

更新为Python 3:

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']]


查看完整回答
反对 回复 2019-10-17
?
繁星淼淼

TA贡献1775条经验 获得超11个赞

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')]

如果csvfile是file对象,则应该用newline=''.
CSV模块



查看完整回答
反对 回复 2019-10-17
  • 3 回答
  • 0 关注
  • 537 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信