Skip to main content
csv_read_python

Read and Write CSV Data Using Python

This tutorial will show you how to make a CSV parser in Python 3. The most common file format for storing plain text data is CSV (comma-separated values). It is one of the most widely used data exchange formats between servers. Each data value is separated by a comma in the CSV files.

Exchanging information through text files is a common way to share info between programs. The python CSV module is a standard library, that has classes and methods to perform read/write operations on CSV files. The pandas’ library has CSV parsing capabilities that require lots of data or numerical analysis.

The csv library will use to parsing data.

You can also checkout other python excel tutorials:

The CSV sample data –

id,employee_name,employee_salary,employee_age,profile_image
"1","Tiger Nixon","320800","61",""
"2","Garrett Winters","170750","63",""
"3","Ashton Cox","86000","66",""

How To Write CSV File Using Python

Let’s create a CSV file(employee.csv) and write into this file. We’ll write to a CSV file using a writer object and the .write_row() method.

import csv
with open('employee.csv', mode='w') as employee_file:
employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

employee_writer.writerow(["5","Dam","1800","61"])
employee_writer.writerow(["6","Hanes","70750","63"])

The response would be as like below information employee.csv file-

5,Dam,1800,61
6,Hanes,70750,63

The writer parameter –

  • csv.QUOTE_MINIMAL – This Instructs the writer objects to only quote those fields which contain special characters such as delimiter, quote char, or any of the characters in line terminator.
  • csv.QUOTE_ALL – This is used to quote all fields.
  • csv.QUOTE_NONNUMERIC – This is used to quote all fields containing text data and convert all numeric fields to the float data type.
  • csv.QUOTE_NONE – This helps to escape quote fields from CSV file. The writer objects to never quote fields.

How To Read CSV File Using Python

Lets’ read csv file using python.I have created employee.csv file using write object, Now I ll read that file and print each row –

import csv
with open('employee.csv', newline='') as csvfile:
  spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
  for row in spamreader:
    print(', '.join(row))

The optional parameter for CSV read method –

  • delimiter – This variable specifies the character used to separate each field. The default is the comma (',').
  • quotechar – This parameter is a delimiter character that used to surround fields. The default is a double quote (' " ').
  • escapechar – This is used to specifies the character used to escape the delimiter character.

One thought to “Read and Write CSV Data Using Python”

Leave a Reply

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