×

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses an interpreter instead of the compiler to run the code.

The interpreted language is processed at the run time thus takes less time to run. Python is also interactive, so we can directly run programs in the terminal itself.

While working in Python, we will often need to read a CSV file and do some operations with the data inside it. The comma-separated files or CSV files are some of the most used files to store the data. In a CSV file, data is stored in a way that a comma separates every value, hence the name Comma-separated file.

The first row denotes the column header. It is pretty common to work with CSV files in Python, and one should have a knowledge of how to deal with them.

We can work with CSV by using the CSV library in Python. Another option is using pandas which is a very powerful library and is very useful in many applications.

An example of a CSV file is:

Id, Name, Age
1, Rahul,21
2, Michael,22

As you can see, the first row denotes the column heading, and a comma separates the data. Here the delimiter is a comma, and we can define any single character as a delimiter in a CSV file.

In this post, we are going to use the CSV library in Python to work with CSV files. It provides the functionality of both reading and writing the CSV files with some other functionalities also.

Writing CSV files

We can also write a CSV file with the help of the CSV library in Python. We can write the CSV file using the writer object from CSV.writer() function. There are multiple ways in which we can write a CSV file using Python. Let us discuss some of them:

Writing CSV using CSV.writerow()

In this case, we will write data in to the CSV file row by row.

Suppose this is the data we want to write in the file:

S.No, City, State

  1. Agra, Uttar Pradesh
  2. New Delhi, Delhi
  3. Mumbai, Maharashtra

Here is the code to write it in a CSV file:

import csv
with open('cities.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["S.No ", " City ", " State "])
writer.writerow([1, " Agra ", " Uttar Pradesh "])
writer.writerow([2, " New Delhi ", " Delhi "])
writer.writerow([3, " Mumbai ", "Maharashtra"])

Output

When we run this code, it will generate a new file named cities.csv in your current directory with the following content:

S.No City State 
1 Agra Uttar Pradesh 
2 New Delhi Delhi 
3 Mumbai Maharashtra
Writing to a CSV file in Python.

In the code, we have imported the CSV module in the first line.

Then open a new file as WRITE mode with the Python open() function.

After that, we are passing that file to the CSV.writer() function, which returns a writer object.

Finally, we are adding each row one by one by using the writerow() function.

Writing Multiple Rows

In this case,we are going to write all the rows of the file in a single line.

To create the data set to export into a CSV file, we must make a list for each row and add all of these rows in a single list. We will also need to define a list of just column headings. Then we pass this data to the CSV.writer() function that returns a writer object that converts the data to write in a CSV file. After that, we will use methods like writerows() to write data into a CSV file.

Let us see the code to write data into a CSV file:

import csv
headers = [“id”, “Name”, “Age”]
rows = [
[1, “Rahul”,21],
[2,”Michael”,22],
[3,”virat”,19]]
with open('students.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(headers)
writer.writerows(rows)

When we run the above code, a students.csv file will be created in the current directory with the following content:

id, Name, Age
1, Rahul,21
2, Michael,22
3, Virat,19
Writing to a CSV file in Python.

If we want to add rows one by one, we can use the method writerow().

Now let us understand the code we have just written:

• import csv
  headers = [“id”, “Name”, “Age”]
  rows = [
[1, “Rahul”,21],
[2,”Michael”,22],
[3,”virat”,19]]

In this part of the code, we import the CSV module and define the headers and rows for the data. The headers contain the column heading, and rows are the data for those headings.

• with open('students.csv', 'w', newline='') as file:
  writer = csv.writer(file)

Here we are first opening the file in write mode, and the object is named a file. After that, we pass the file object to the CSV.writer() function, which will convert the file object to the CSV.writer object. We are saving this object as a writer.

• writer.writerow(headers)
  writer.writerows(rows)

Here in the first line of code, we are writing the headers with the writer's method, and in the second line, we are writing rows since rows contain multiple lines of data, so the method used id writers.

Writing CSV file with Custom Delimiter.

By default, CSV files are separated by commas, which means the default delimiter of a CSV file is a comma. However, we can also define our custom delimiter in CSV files like '|' or '\t'.

If we want to specify our custom delimiter, we can pass the additional perimeter delimiter to the CSV.writer() function.

Let us use the delimiter '|' in the previous example data.

import csv
headers = ["id", "Name", "Age"]
rows = [
[1, "Rahul",21],
[2,"Michael",22],
[3,"Virat",19]]
with open('students.csv', 'w', newline='') as file:
writer = csv.writer(file,delimiter = "|")
writer.writerow(headers)
writer.writerows(rows)

Output

Running this code will generate a CSV file with delimiter as "|".

id|Name|Age
1|Rahul|21
2|Michael|22
3|Virat|19
Writing to a CSV file in Python.

Writing Dictionary to CSV files

We can write a Python dictionary to a CSV file by using the objects of csv.DictWriter() class. The syntax for the csv.DictWriter() class is:

csv.DictWriter(file, fieldnames)

Here, the file is the file name where we want to write the dictionary, and field names are the list of column headings describing the order in which data is present. The basic logic is similar to writing data in a CSV file, but here, instead of defining the rows, we have to define a list of a dictionary that contains the data to be written. Use the following code to write a dictionary to a CSV file:

import CSV


mydict =[{'branch': 'CSE', 'name': 'Nikhil', 'year': '4'},
         {'branch': 'CSE', 'name': 'Rahul', 'year': '1'},
         {'branch': 'IT', 'name': 'Michael', 'year': '2'},
         {'branch': 'ECE', 'name': 'Sagar', 'year': '3'},
         {'branch': 'ME', 'name': 'Roahan', 'year': '3'},
         {'branch': 'EEE', 'name': 'Virat', 'year': '1'}]


fields = ['name', ‘branch’, 'year',]


with open(‘students_data.csv’, 'w') as file:
writer = csv.DictWriter(file, fieldnames = fields)      
writer.writeheader()
writer.writerows(mydict)

After running the code, a file called students_data.csv will get created in your current directory with the following content:

name,branch,year


Nikhil, CSE,4


Rahul,CSE,1


Michael, IT,2


Sagar, ECE,3


Rohan, ME,3


Virat, EEE,1
Writing to a CSV file in Python.

Now let us understand the code we have just written:

• import CSV


mydict =[{'branch': 'CSE', 'name': 'Nikhil', 'year': '4'},
         {'branch': 'CSE', 'name': 'Rahul', 'year': '1'},
         {'branch': 'IT', 'name': 'Michael', 'year': '2'},
         {'branch': 'ECE', 'name': 'Sagar', 'year': '3'},
         {'branch': 'ME', 'name': 'Roahan', 'year': '3'},
         {'branch': 'EEE', 'name': 'Virat', 'year': '1'}]


fields = ['name', ‘branch’, 'year',]

In this part of the code, we import the CSV module and define the dictionary, which contains all the data in a Python dictionary format, and the fieldname, which are nothing but column headings. These fieldnames define the order in which columns get written in a CSV file.

• with open(‘students_data.csv’, 'w') as file:
  writer = csv.DictWriter(file, fieldnames = fields)      

Here we are first opening the file in write mode, and the object is named as the file. After that, we are passing the file object to CSVthe .writer() function, which will convert the file object to CSV.writer object, and the fieldnames are specified as an argument that contains the column headings. We are saving this object as a writer.

• writer.writeheader()
  writer.writerows(mydict)

Here in the first line of code, the writeheader method writes the first line of the file by using the given fieldnames arguments. In the second line, we are writing the dictionary to the file since rows contain multiple data lines, so the method used id writers.


Related Topics

Python Knapsack problem

Python Knapsack problem Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem. What is a knapsack problem? A problem from the...

5 minutes read.

Uint8 Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

How to set up a proxy using selenium in python

What is Proxy? A proxy acts as a middleman between user requests and server responses. The main purposes of proxies are to protect user privacy and encapsulate data between various interactive...

3 minutes read.

Python object()

Python object() class The object class in Python is a base for all classes. It returns a new featureless object. Syntax class object Parameter NA Return It returns a new featureless object. Example 1 # Python program explaining # the object()...

1 minute read.

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

Python String join() method

Python String join() method The String.join() method in Python concatenates each element of an iterable (such as list, string and tuple) to the given string and returns the concatenated string. Syntax string.join(seq) Parameter Seq: This...

1 minute read.

Python MySQL Delete Operation

Python MySQL Delete Operation: Like the update operation where we were updating required field from a SQL table, we can also delete an entry from the table which we have...

4 minutes read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

Composition in Python

Composition in Python Composition is one of the important concepts of Object-oriented programming (OOPs). Composition basically enables us for creating complex types objects by combining other types of objects in the...

6 minutes read.

Python Generator

Python Generator: A Function is said to be a Python Generator that produces or generates a sequence of results. A Python Generator maintains its native state to work so that...

6 minutes read.

Python Goto Statement

We all know that Python is the most basic and widely used programming language in the world. It is also one of the world's most popular and widely used languages....

4 minutes read.

Falcon Python

Introduction of Python Python is the fastest and the smartest programming language and it is an object oriented language. Python has libraries that can be importedeasily and perform many operations; to...

3 minutes read.

Python String upper() method

Python String upper() method The string.upper() method in Python returns a copy of the string converted to uppercase. Syntax string.upper() Parameter NA Return This method returns a copy of the string converted to uppercase. Example 1 # Python...

1 minute read.

Python sum() function

Python sum() function The sum() function in python sums start and the items of an iterable from left to right and returns the total.  Syntax sum(iterable[, start]) Parameter iterable: This parameter represents the sequence to sum. start: It is optional...

1 minute read.

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

Why learn Python?

All things considered, learning python would be extraordinary, it'll acquaint you with the universe of dynamic programming dialects, if you're somebody who has had a semester of involvement with C. Python...

4 minutes read.

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal

Python Program to Convert Decimal into Binary, Octal, and Hexadecimal We know that the most widely used number system is a decimal system, but the computer only understands binary values. The...

2 minutes read.

Difference Between Python and Scala

What is Python? Python is a high-level general-purpose interpreted programing language. It is used for multi general-purpose work such as language construct as well as its object-oriented approach aims to help...

4 minutes read.

App Config Python

An XML file called App. Config serves as the document for any programme. In other terms, you can modify any configuration inside of it without going to edit the code...

7 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.