Python csv

CSV introduction

read data from csv file

  • use csv module to read the data from file.
  • look at the below csv file

/tmp/products.csv

product_name, asin
Redmi 9A Sport, B09GFLXVH9
Dell Intel 5th Gen, B07SN9P55R
MacBook Air, B07SN8P55R
  • look at the below code

import csv

file_path = "/tmp/products.csv"
with open(file_path, 'r') as _file:
    csv_reader = csv.reader(_file, delimiter=',')
    for row in csv_reader:
        print(row)
* above program gives the below output.

['product_name', ' asin']
['Redmi 9A Sport', ' B09GFLXVH9']
['Dell Intel 5th Gen', ' B07SN9P55R']
['MacBook Air', ' B07SN8P55R']
  • from the above output, we can see that when we iterate over the reader it gives list.
  • we can also read the data as dictionary. It treats the first row as header.
  • let's look at the code for that
import csv

file_path = "/tmp/products.csv"
with open(file_path, 'r') as _file:
    csv_reader = csv.DictReader(_file)
    for row in csv_reader:
        print(row)
  • above code gives the below output

{'product_name': 'Redmi 9A Sport', ' asin': ' B09GFLXVH9'}
{'product_name': 'Dell Intel 5th Gen', ' asin': ' B07SN9P55R'}
{'product_name': 'MacBook Air', ' asin': ' B07SN8P55R'}
* when we use csv.DictReader(file) it reads, the each row as dict.

write data to csv file

  • we can use csv.writer(file) or csv.DictWriter(file, fieldnames)
  • let's use csv.writer(file) in the below code.
import csv

file_path = "/tmp/students.csv"
with open(file_path, 'w') as _file:
    header = ["first_name", "last_name"]
    data = [
        ["Anji", "B"],
        ["Shiva", "D"],
        ["Sathyam", "M"],
        ["Rajeswari", "D"]
    ]

    # write to file
    writer = csv.writer(_file)
    # write header
    writer.writerow(header)
    # write data
    writer.writerows(data)
  • After running the program, just run command cat /tmp/students.csv to see the file contents.
first_name,last_name
Anji,B
Shiva,D
Sathyam,M
Rajeswari,D
  • Now, let's use csv.DictWriter(file, fieldnames)
import csv

file_path = "/tmp/students.csv"
with open(file_path, 'w') as _file:
    header = ["first_name", "last_name"]
    row1 = {"first_name": "Anji", "last_name": "B"}
    data = [
        {"first_name": "Shiva", "last_name": "D"},
        {"first_name": "Sathyam", "last_name": "M"},
        {"first_name": "Rajeswari", "last_name": "B"}
    ]

    # write to file
    writer = csv.DictWriter(_file, header)
    # write header
    writer.writeheader()
    # write a single row
    writer.writerow(row1)
    # write multiple rows at once
    writer.writerows(data)
  • csv.DictWriter(_file, header) contains below methods
    • writeheader() - write the header
    • writerow(row) - writes a single row (i.e dict)
    • writerows([row1, row2, ...]) - writes multiple rows

Note: Try these examples and read official docs for advanced usage

Reference: