Wednesday 23 March 2016

Import CSV ke Database dengan Header Sebagai Nama Kolom

Status : Draft


from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('postgresql://username:password@localhost/nama_database')
df = pd.read_csv('/path/ke/file/csv')
df.to_sql('nama_tabel', engine)
Jika hanya ingin mengimport beberapa baris saja, tinggal tambahkan paramater nrows di read_csv : pd.read_csv('/path/ke/file/csv', nrows=20)

Kalau ingin mengimpot seluruh csv yang berada pada sebuah direktori :

import os
from sqlalchemy import create_engine
from os.path import basename
import pandas as pd 
for file in os.listdir("/path/to/csv/dir"):
    if file.endswith(".csv"):
        engine = create_engine('postgresql://username:password@localhost/nama_database')
        print file
        df = pd.read_csv(file, nrows=20)
        df.to_sql(os.path.splitext(file)[0].lower(), engine)

Kemudian melakukan proses import data lebih lanjut dengan tool lain seperti Pentaho Data Integration. Karena jika data CSV cukup besar, dan sumber daya terbatas, sistem operasi dapat hang. 

Referensi


  1. How to copy from CSV file to PostgreSQL table with headers in CSV file?, http://stackoverflow.com/questions/17662631/how-to-copy-from-csv-file-to-postgresql-table-with-headers-in-csv-file


No comments:

Post a Comment