วันพฤหัสบดีที่ 23 มกราคม พ.ศ. 2563

python ดึงข้อมูล .csv แล้ว insert เข้า mongoDB

import os
import csv
from pymongo import MongoClient


connection = MongoClient("mongodb://myuser:mypassword@localhost:27017")
# insert your data for database_name and collection_name
db = connection.database_name.collection_name


path="E:/TESTING/mongo_test"            
list_of_files = {}
for filename in os.listdir(path):
     # if the element is a csv file then..
     if filename[-4:] == ".csv":
         list_of_files[filename] = path + "\\" + filename
         print   (list_of_files[filename])
         with open(list_of_files[filename], encoding="utf8" ) as f:
            csv_f = csv.reader(f)
            for i, row in enumerate(csv_f):
               #if i > 5 and len(row) > 1 :
                 print(row)
                 db.insert({'F1': row[0], 'F2': row[1]})
                
# find all documents
results = db.find()

print()
print('==============================')

# display documents from collection
for record in results:
   # print out the document
   print(record['F1'] + ',',record['F2'])

print()

# close the connection to MongoDB
connection.close()