Skip to content

Python write list to CSV file

  • by

Use an in-built CSV module to write a list into a CSV file in Python. A CSV file is a bounded text format that uses a comma to separate values.

import csv

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

Python writes a list to a CSV file

A simple example code converts a list to CSV by importing an in-built CSV module in Python.

import csv

fields = ['Employee', 'ID', 'Salary']

rows = [['John', '011', '2000'],
['Tim', '012', '8000'],
['Kin', '351', '5000'],
['Pink', '146', '10000']]

with open('EmployeeData.csv', 'w') as f:
csv_writer = csv.writer(f)
csv_writer.writerow(fields)
csv_writer.writerows(rows)

Output:

Python write list to CSV file

Writes a list to CSV pandas

import pandas as pd  
name = ["sonu", "monu"] 
subjects= ["Maths", "English"]
marks = [45, 65,] 
dictionary = {'name': name, 'subjects': subjects, 'marks': marks}  
dataframe = pd.DataFrame(dictionary) 
dataframe.to_csv('name.csv')

Write a list to CSV numpy

import numpy as np 
rows = [ ['Sonu', 'maths', '45'],  
         ['Monu', 'english', '25'],  
         ['Ammu', 'hindi', '35']] 
np.savetxt("student.csv",rows, delimiter =" ",  fmt ='% s') 

Do comment if you have any doubts or suggestions on this Python write file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *