Python CSV File – Read & Write – CSV API

Csv File Open

Looking for simplest Python CSV codes?

We have here – code for both Python Csv read & write, using the CSV api.

The code uses the commands in the following order to perform CSV file operations.

  1. File Open: First the file name & then the open mode. If it is read then ‘r’ & write mode is mentioned as ‘w’.¬†Syntax: open (filepath, OpenMode,[encoding – UTF etc.,)
  2. Create CSV reader or writer object & assign to the above file.
  3. Read rows or write data

That’s it. Now, get the code.

Python Csv Write or Create Csv File

This example write a row of data passed as array format parameter.

Code Execution: Copy paste this code Python IDE, save with extension .py & execute by pressing F5.

import csv
#Write to CSV File
with open('D:\Python_CSV_ReadWrite.csv', 'w', newline='') as csvfile:
    csvfilewriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    csvfilewriter.writerow(['1', 'officetricks', 'https://officetricks.com'])
print("Wrinting Process Complete")

Use this code to Write to CSV File from Python using the csv api. Once the code execution is completed, open the output file & verify the data is written correctly.

Python Read Csv

This CSV reader example, reads data from a Csv file. There are 3 loops in it. First loop reads each row, second loop reads each column from every row. The 3rd loop reads each character in each row.

You can use any of the loop that is applicable to you need.

import csv
#Read From CSV File
with open('D:\Python_CSV_ReadWrite.csv', 'r', newline='') as csvfile:
    csvfilereader = csv.reader(csvfile, delimiter=',', quotechar='|')
    #Print each Row
    for row in csvfilereader:         
        print(row)
        #Print Each Column or Cell
        for col in row:     
             print (col)
             #Print each Character
             for ch in col:
                 print(ch)
print("Reading Process Complete")

If you execute this code, it will print the data read from the csv file. In most cases you don’t require the third loop. We will not be reading each character from a CSV file – not always.

Leave a Reply