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?
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') .
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.
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.
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']]
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With