import csv python,Python导入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')]

How can import this this csv to the list I need using Python?

解决方案

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

If you need tuples:

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