Python导入csv到列表 [英] Python import csv to list
本文介绍了Python导入csv到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含约2000条记录的CSV文件。
I have a CSV file with about 2000 records.
每个记录都有一个字符串和一个类别。
Each record has a string, and a category to it.
This is the first line, Line1
This is the second line, Line2
This is the third line, Line3
我需要将这个文件读入一个看起来像这样的列表:
I need to read this file into a list that looks like this;
List = [('This is the first line', 'Line1'),
('This is the second line', 'Line2'),
('This is the third line', 'Line3')]
如何将此 csv
导入列表我需要使用Python吗?
How can import this this csv
to the list I need using Python?
推荐答案
使用 csv
模组(Python 2.x):
Use the csv
module (Python 2.x):
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']]
如果您需要元组:
import csv
with 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')]
Python 3.x版本(由@seokhoonlee下面)
Python 3.x version (by @seokhoonlee below)
import csv
with 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']]
这篇关于Python导入csv到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文