Read Write File CSV Menggunakan Python

 


Berikut adalah cara read write file CSV menggunakan Phyton :

1. Buat file csv : data.csv

NO,NAMA,ALAMAT

NO,NAMA,TELEPON

1,Bambang,081234

2,Richard,08712333

3,Bapak Budi,08733311

4,Jokowi Dodo,0851231


catatan : gunakan tanda petik untuk kata yang mengandung koma, seperti gelar

contoh : 

1,"Bambang, S.Kom",Bandung


2. Buat file phyton : bacacsv.py

import csv

with open('data.csv') as csv_file:

    csv_reader = csv.reader(csv_file, delimiter=",")

    print(csv_reader)

    for row in csv_reader:

        print(row)

Output :


Catatan : Untuk format bisa disesuaikan dengan csv file

# membaca CSV dengan dlimiter tab

csv.reader(csv_file, delimiter="\t")

# membaca CSV dengan dlimiter titik dua :

csv.reader(csv_file, delimiter=":")

# membaca CSV dengan dlimiter titik koma ;

csv.reader(csv_file, delimiter=";")


3. Parsing File CSV di Python : parse_dic.py

3.1. Parsing CSV menjadi List

contoh 1 :

import csv

contacts = []

with open('data.csv') as csv_file:

    csv_reader = csv.reader(csv_file, delimiter=",")

    for row in csv_reader:

        contacts.append(row)

print(contacts)

Output :

[['NO', 'NAMA', 'TELEPON'], ['1', 'Bambang', '081234'], ['2', 'Richard', '08712333'], ['3', 'Bapak Budi', '08733311'], ['4', 'Jokowi Dodo', '0851231']]


Contoh 2 :

import csv

contacts = []

with open('data.csv') as csv_file:

    csv_reader = csv.reader(csv_file, delimiter=",")

    for row in csv_reader:

        contacts.append(row)

labels = contacts.pop(0)

print(labels)

print(contacts)

Output :

#isi list labels:

['NO', 'NAMA', 'TELEPON']

# isi list contacts:

[['1', 'Bambang', '081234'], ['2', 'Richard', '08712333'], ['3', 'Bapak Budi', '08733311'], ['4', 'Jokowi Dodo', '0851231']]


Contoh 3 :

import csv

contacts = []

with open('data.csv') as csv_file:

    csv_reader = csv.reader(csv_file, delimiter=",")

    for row in csv_reader:

        contacts.append(row)

labels = contacts.pop(0)

#print(labels)

#print(contacts)

print(f'{labels[0]} \t {labels[1]} \t\t {labels[2]}')

print("-"*34)

for data in contacts:

    print(f'{data[0]} \t {data[1]} \t {data[2]}')

Output :


3.2. Parsing CSV menjadi Dictionary

Contoh 1 :

import csv

contacts = []

with open('data.csv') as csv_file:

    csv_reader = csv.DictReader(csv_file)

    for row in csv_reader:

        contacts.append(row)

print(contacts)

Output :

[OrderedDict([('NO', '1'), ('NAMA', 'Bambang'), ('TELEPON', '081234')]), OrderedDict([('NO', '2'), ('NAMA', 'Richard'), ('TELEPON', '08712333')]), OrderedDict([('NO', '3'), ('NAMA', 'Bapak Budi'), ('TELEPON', '08733311')]), OrderedDict([('NO', '4'), ('NAMA', 'Jokowi Dodo'), ('TELEPON', '0851231')])]


Contoh 2 :

import csv

contacts = []

with open('data.csv') as csv_file:

    csv_reader = csv.DictReader(csv_file)

    for row in csv_reader:

        contacts.append(row)

print("NO \t NAMA \t\t TELEPON")

print("-" * 32)

for data in contacts:

    print(f"{data['NO']} \t {data['NAMA']} \t {data['TELEPON']}")

Output :



4. Write file csv : tulis_csv_list.py

4.1. Menulis Data List ke CSV

import csv

with open('data.csv', mode='a') as csv_file:

    # membuat objek writer

    writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    # menulis baris ke file CSV

    writer.writerow(["5", "Dian", "021100022"])

    writer.writerow(["6", "Meli", "0214444432"])

print("Writing Done!")

Output : 

jalankan kemudian jalan kan juga file parse_dic.py


4.2. Menulis Data Dictionary ke CSV

import csv

with open('data.csv', mode='a') as csv_file:

    # menentukan label

    fieldnames = ['NO', 'NAMA', 'TELEPON']

    # membuat objek writer

    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

    # menulis baris ke file CSV

    writer.writeheader()

    writer.writerow({'NO': '10', 'NAMA': 'Via Vallen', 'TELEPON': '02109999'})

    writer.writerow({'NO': '11', 'NAMA': 'M. Andi', 'TELEPON': '02148488888'})

print("Writing Done!")

Output :

jalankan kemudian jalan kan juga file parse_dic.py