Python – Read & Write .csv

READ DATA

content.csv

NO,NAME,PHONE
1,Joe,081234
2,Richard,082345
3,Mark,083456

app.py

Example 1 (Print List) :

import csv

contacts = []

with open('contacts.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=",")
    for row in csv_reader:
        contacts.append(row)

labels = contacts.pop(0)
# contacts.pop(0) = remove label

print(labels)
print(contacts)

Result :
['NO,NAME,PHONE']
[['1,Joe,081234'], ['2,Richard,082345'], ['3,Mark,083456']]

WRITE DATA

Example 1 :

import csv

with open('contacts.csv', mode='a', newline='') as csv_file:
    # Create object
    writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    # Write
    writer.writerow(["NO", "NAME", "PHONE"])
    writer.writerow(["1", "Ava", "0212345"])
    writer.writerow(["2", "Chezter", "0234567"])

print("Writing Done!")

List to CSV

Example 2 :

import csv

data = [
    ["ava", "0212345"], ["chezter", "0212345"], ["sky", "0212345"]
]

with open('contacts.csv', mode='w', newline='') as csv_file:
    # Create object
    writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    # Write
    writer.writerow(["NAME", "PHONE"])

    for d in data:
        writer.writerow(d)

print("Writing Done!")

Dictionary to CSV

import csv

data = [
    {
      "NAME": "AVA",
      "PHONE": "0212345"
    },
    {
      "NAME": "CHEZTER",
      "PHONE": "0212345"
    },
    {
      "NAME": "SKY",
      "PHONE": "0212345"
    }
]

with open('contacts.csv', mode='w', newline='') as csv_file:

    # fieldnames
    fieldnames = ['NAME', 'PHONE']

    # Create writer object
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

    # Write
    writer.writeheader()

    for d in data:
        writer.writerow(d)

print("Writing Done!")

Leave a Reply

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