how to convert list into csv in python code example

Example 1: how to convert list into csv in python

import pandas as pd    

list1 = [1,2,3,4,5]
df = pd.DataFrame(list1)
df.to_csv('filename.csv', index=False)

#index =false removes unnecessary indexing/numbering in the csv

Example 2: list to csv

import csv

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(a)

Example 3: how to convert csv into list

open('file.csv', 'r').read().splitlines() #assuming you want each row to be an individual element in the list

Tags: