Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python import csv to list

Tags:

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:

data = [('This is the first line', 'Line1'),         ('This is the second line', 'Line2'),         ('This is the third line', 'Line3')] 

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

like image 345
MorganTN Avatar asked Jul 09 '14 19:07

MorganTN


People also ask

How do I convert a CSV file to a list in Python?

CSV: Import the csv module in Python, create a csv writer object, and write the list of lists to the file in using the writerows() method on the writer object. Pandas: Import the pandas library, create a Pandas DataFrame, and write the DataFrame to a file using the DataFrame method DataFrame. to_csv('file. csv') .

How do you read a CSV file in a list in Python?

csv file in the read mode 'r'. We pass the read_obj to the csv. reader() method while creating an object to read the csv file. Then, we convert each row of the CSV into a tuple using a map function and at last convert the whole data into a list.

How do I import a CSV file into an array in Python?

Python NumPy read CSV into 2d NumPy arraytxt() and open() functions to load a CSV file into a 2Dimension NumPy Array. Call open file to open the CSV text file Use numpy. loadtxt( CSV file, delimiter) with the file as the result of the previous step and delimiter as “,” to return the data in a two-dimensional NumPy.


2 Answers

Using the csv module:

import csv  with open('file.csv', newline='') as f:     reader = csv.reader(f)     data = list(reader)  print(data) 

Output:

[['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('file.csv', newline='') as f:     reader = csv.reader(f)     data = [tuple(row) for row in reader]  print(data) 

Output:

[('This is the first line', 'Line1'), ('This is the second line', 'Line2'), ('This is the third line', 'Line3')] 

Old Python 2 answer, also using the csv module:

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']] 
like image 73
Maciej Gol Avatar answered Sep 20 '22 17:09

Maciej Gol


Updated for Python 3:

import csv  with open('file.csv', newline='') as f:     reader = csv.reader(f)     your_list = list(reader)  print(your_list) 

Output:

[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']] 
like image 44
seokhoonlee Avatar answered Sep 21 '22 17:09

seokhoonlee