how to read csv data in python code. python reading csv file example

Read CSV data in Python Code

Here we learn how to read CSV data in python code, CSV indicates comma separated values, that can be stored in plain text file, instead of comma separate we can have other character as a separator like pipe (|)

python csv example

CSV is one of the most commonly used file format for exchanging data into multiple system and for human reading.

In python, we have built-in library to deal with CSV file. we just need to import the library by adding the reference import csv

To read the file we need to open the reader object by using csv.reader(csv_file, delimiter=',')

import csv
csvPath ="testdata\\students.txt"
with open(csvPath) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')    
    #totalRecord =len(list(csv_reader1))
    line_count = 0
    for row in csv_reader:       
        if line_count == 0:
            print(f'Column names: {", ".join(row)}')
            line_count += 1
        else:
            if row: 
                print(f'\t{row[0]}, {row[1]},  {row[2]}.')                           
                line_count += 1
    print(f'Processed {line_count} lines.')

While reading values row by row make sure you use if row: , that indicates reading next row only if the row exists, otherwise that will throw list index out of range error.

In case you want to find how many rows are there in the CSV file, you can simply use the len and list function with the reader object len(list(csv_reader1))

Write CSV in python

So far, we have seen how to read CSV data from text file using python code, now we see how to write back values in comma separated format to the same file.

Here in example we demonstrate how to write hardcoded data into csv file, but in real-time situation, you may fetch data from mysql database or other data sources then write to CSV file, still the code will remain same apart from fetching data part.

Like reading CSV, we need to open the file and then create a writer instance using csv.writer(student_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

import csv

csvPath ="testdata\\students.txt"

with open(csvPath, mode='w') as student_file:
    student_writer = csv.writer(student_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    student_writer.writerow(['Name', 'email', 'mobile'])
    student_writer.writerow(['Arindam', 'arindam@email.com', '975412478'])
    student_writer.writerow(['Anushka', 'anushka@email.com', '987412142'])
    student_writer.writerow(['Ronita', 'ronita@email.com', '874412142'])
    student_writer.writerow(['Debargha', 'debargha@email.com', '874512142'])
    student_writer.writerow(['Gargi', 'gargi@email.com', '870234122'])

If you want to write dynamic record, then you need to use write row function only once student_writer.writerow(['Arindam', 'arindam@email.com', '975412478']), instead of hardcoded values, set your dynamic values from database.

You may be interested to read following tutorials

 
Read XML Python
Python CSV example
Python programming examples | Join Python Course