I have a CSV file with about 200.000 records.
Each record has a title number, and some string information:
Title_1, Line_1_1, Line_1_2
Title_2, Line_2_1, Line_2_2
Title_3, Line_3_1, Line_3_2
I need to read this file into a list that looks like this:
data = [[Title_1, Line_1_1, Line_1_2], [Title_2, Line_2_1, Line_2_2], [Title_1, Line_3_1, Line_3_2]]
How can import this CSV to the list I need using Python?
CodePudding user response:
--- Hi, fellow new contributor! :)
Might not be the most direct way, but my initial thought is to import via Python's Pandas library!
import pandas as pd
your_file_path = "route1/route2/csv_file.csv"
df = pd.read_csv("your_file_path")
df.head(5)
With your CSV in a dataframe format, you can now pull the values you want out into a list.
output_ls = []
for index, row in df.itertuples():
output_ls.append([row])
Haven't tested the code, but give it a try and let me know!
CodePudding user response:
import csv
with open("yourcsv.csv", newline="") as y:
data = csv.reader(y)
data_list = list(data)
print(data_list)