Creating and Saving Data to CSV Files with Python

Save Results To CSV File With Python

CSV files or “comma separated values” files are similar to Excel sheets and they have “.csv” extensions. They are used to store information separated by commas in a tabular manner. This is the most common way of storing data records for huge data systems.

There are rows and columns in a csv file just like in a table. The rows are referred to as data records and the columns are the fields.

Since CSV files are simple text files, they are easier to use for website development. The CSV files can also be exported easily in spreadsheets and used in database management systems without much trouble. They also come in handy when we need to organize large quantities of data.

Creating a CSV File in Python: The Basics

There are mainly four steps to creating a CSV file in python. They are:

  • We need to open() the file in the write(‘w’) mode.
  • Next we will create a writer() object that will help us write data into the CSV file.
  • In the third step, we will use the writerows() or writerow() function to write the rows in the file.
  • Finally saving and closing our file.

To create and save data to a CSV file in Python, use the built-in ‘csv’ module. There are two main classes, ‘csv.writer’ and ‘csv.DictWriter’, which help create and write data into CSV files. Use the ‘writerow()’ or ‘writerows()’ functions for the ‘csv.writer’ class, and ‘writeheader()’ for the ‘csv.DictWriter’ class.

Similar: Convert a CSV file to an array in Python.

Methods for Writing to CSV Files in Python

There are mainly two types of writers for csv files. They both can be used to write data into csv files. The two classes are:

  • csv. writer class– It is used to write data into CSV files. It is a writer object that converts information into delimited strings. The syntax of the function is csv. writer(name_or_path_of_file). This is the most common way of writing a CSV file in Python from lists. This class provides two types of functions.
  • The writerow() function, writes new rows or data records one by one inside the csv file when its open.
  • The writerows() function, which writes new rows all together inside a csv file when used.
  • Another class of CSV writers is the csv.dictWriter class which as the name suggests, writes Python dictionaries into CSV files. The syntax is : csv.DictWriter(filename,fieldnames) where, the filename is the name of the required file and the field name is the name of each column. This class only has one function.
  • The writeheader() function, which only writes the first row using the column names.

Method 1: Writing to CSV Files with csv.writer Class

Let’s write the results of 4 students called Varun, Rahul, Kabir, and Suman in 4 subjects namely, English, Math, Science, and Social Science into a csv file called student_results.csv. We will open the file using with open() function which eliminates the need of explicitly closing a file at the end of a program.

# importing required module
import csv

# opening the file
with open("student_results.csv", "w", newline="") as f:
    # creating the writer
    writer = csv.writer(f)
    # using writerow to write individual record one by one
    writer.writerow(["Name", "English", "Math", "Science", "Social Science"])
    writer.writerow(["Varun", "91", "90", "74", "80"])
    writer.writerow(["Rahul", "89", "94", "81", "86"])
    writer.writerow(["Kabir", "80", "93", "88", "82"])
    writer.writerow(["Suman", "80", "75", "98", "85"])

The above can also be re-written using the writerows() function all at once inside one list as shown below:

# importing required module
import csv

# opening the file
with open("student_results.csv", "w", newline="") as f:
    # creating the writer
    writer = csv.writer(f)
    # using writerows, all rows at once
    Our_list = [
        ["Name", "English", "Math", "Science", "Social Science"],
        ["Varun", "91", "90", "74", "80"],
        ["Rahul", "89", "94", "81", "86"],
        ["Kabir", "80", "93", "88", "82"],
        ["Suman", "80", "75", "98", "85"],
    ]
    writer.writerows(Our_list)

Both the above blocks of codes will give you the same result when you open and view your csv file called “students_results.csv”

Name,English,Math,Science,Social Science
Varun,91,90,74,80
Rahul,89,94,81,86
Kabir,80,93,88,82
Suman,80,75,98,85
Using The Writer Class
Using The Writer Class

Voila! you have successfully written in a csv file using Python.

Also read : How to combine CSV files using Python?

Method 2: Writing to CSV Files with csv.DictWriter Class

In this example, we will set the field names as the keys of the dictionaries and the individual values as the data in each row. We will use the same data from the above example that is, the 4 names and the marks obtained in the 4 subjects. We will club all of the information into one single dictionary and write that using the writeheader() function. Let’s look at it’s implementation.

# importing required module
import csv

# creating the dictionary
Our_dict = [
    {
        "Name": "Varun",
        "English": "91",
        "Math": "90",
        "Science": "80",
        "Social Science": "93",
    },
    {
        "Name": "Rahul",
        "English": "94",
        "Math": "75",
        "Science": "88",
        "Social Science": "70",
    },
    {
        "Name": "Kabir",
        "English": "81",
        "Math": "99",
        "Science": "91",
        "Social Science": "89",
    },
    {
        "Name": "Suman",
        "English": "92",
        "Math": "97",
        "Science": "94",
        "Social Science": "71",
    },
]

# extracting fieldnames
columns = ["Name", "English", "Math", "Science", "Social Science"]

# opening the file
with open("student_results.csv", "w", newline="") as f:
    # using dictwriter
    writer = csv.DictWriter(f, fieldnames=columns)
    # using writeheader function
    writer.writeheader()

The output would be the same as the above section.

Name,English,Math,Science,Social Science
Varun,91,90,80,93
Rahul,94,75,88,70
Kabir,81,99,91,89
Suman,92,97,94,71

Conclusion: Mastering CSV Files with Python

it is very easy to write data into csv files using the built in module in Python called csv. The full form of CSV is Comma Separated Values. It stores data in the form of tables making it easier to read and organized. It is useful when there is huge about of data and also in database management systems. We have gone through the various ways and functions that can be used to write into CSV files from python. Thank you for reading!