Masih Bingung Kelola File .csv Dengan Python?

Penggunaan Modul .csv

Pada bagian ini akan digunakan modul .csv untuk pengelolaan file .csv. Berikut ini kode programnya:

import csv
from datetime import datetime

path = "page_visits_2.csv"
file = open(path, newline="")
pembaca = csv.reader(file)

# baris pertama merupakan judul
judul = next(pembaca)

data = []
for baris in pembaca:
    # baris = ['first_name', 'last_name', 'gender', 'age', 'visit_date', 'website_goal']
    first_name = baris[0]
    last_name = baris[1]
    gender = baris[2]
    age = int(float(baris[3]))
    visit_date = datetime.strptime(baris[4], '%Y-%m-%d')
    website_goal = baris[5]
    data.append([first_name, last_name, gender, visit_date,
                 age, website_goal])

print(judul)
for baris in data:
    print(baris)

Berikut ini keluaran dari program tersebut dalam bentuk list dengan tipe data yang telah disesuaikan

['first_name', 'last_name', 'gender', 'age', 'visit_date', 'website_goal']
['James', 'Mcguire', 'male', datetime.datetime(2017, 10, 26, 0, 0), 50, 'Find a job']
['John', 'Vaughan', 'male', datetime.datetime(2017, 11, 9, 0, 0), 35, 'Pay a bill']
['Robert', 'Dillon', 'male', datetime.datetime(2017, 11, 28, 0, 0), 33, 'Pay a bill']
['Michael', 'Cameron', 'male', datetime.datetime(2017, 9, 27, 0, 0), 40, 'When is trash day?']
['William', 'Yang', 'male', datetime.datetime(2017, 11, 1, 0, 0), 38, 'Contact City Council']
['David', 'Trujillo', 'male', datetime.datetime(2017, 10, 24, 0, 0), 31, 'Find a job']
['Richard', 'Koch', 'male', datetime.datetime(2017, 10, 12, 0, 0), 28, 'Contact City Council']
['Charles', 'French', 'male', datetime.datetime(2017, 9, 11, 0, 0), 14, 'Find a job']
['Joseph', 'Humphrey', 'male', datetime.datetime(2017, 10, 27, 0, 0), 50, 'Find a job']
['Thomas', 'Strickland', 'male', datetime.datetime(2017, 10, 6, 0, 0), 46, 'Find a job']
['Christopher', 'Waller', 'male', datetime.datetime(2017, 9, 19, 0, 0), 65, 'When is trash day?']
['Daniel', 'Stephenson', 'male', datetime.datetime(2017, 9, 5, 0, 0), 29, 'Find a job']
['Paul', 'Berg', 'male', datetime.datetime(2017, 10, 16, 0, 0), 39, 'When is trash day?']
['Mark', 'Townsend', 'male', datetime.datetime(2017, 9, 4, 0, 0), 52, 'Pay a bill']
['Donald', 'Schneider', 'male', datetime.datetime(2017, 12, 24, 0, 0), 27, 'Contact City Council']

Semoga cara ini bisa bermanfaat. Tulis pada bagian komentar bila ada pertanyaan.

Be the first to comment

Leave a Reply

Your email address will not be published.


*