我有一個CSV文件是這樣的:類型錯誤:沒有足夠的論據格式的字符串,而插入到mysql數據庫
[email protected], 01-05-2014
[email protected], 01-05-2014
[email protected], 01-05-2014
[email protected], 01-05-2014
我讀上面的CSV文件,並提取域名,也電子郵件地址由計數域名和日期。所有這些我需要插入MySQL表中的所謂的域。
下面是代碼,其中給我的錯誤爲TypeError: not enough arguments for format string
,它發生在我嘗試插入domains
表中時發生。
#!/usr/bin/python
import fileinput
import csv
import os
import sys
import time
import MySQLdb
from collections import defaultdict, Counter
domain_counts = defaultdict(Counter)
# ======================== Defined Functions ======================
def get_file_path(filename):
currentdirpath = os.getcwd()
# get current working directory path
filepath = os.path.join(currentdirpath, filename)
return filepath
# ===========================================================
def read_CSV(filepath):
with open('emails.csv') as f:
reader = csv.reader(f)
for row in reader:
domain_counts[row[0].split('@')[1].strip()][row[1]] += 1
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
passwd="abcdef1234", # your password
db="test") # name of the data base
cur = db.cursor()
q = """INSERT INTO domains(domain_name, cnt, date_of_entry) VALUES(%s, %s, STR_TO_DATE(%s, '%d-%m-%Y'))"""
for domain, data in domain_counts.iteritems():
for email_date, email_count in data.iteritems():
cur.execute(q, (domain, email_count, email_date))
db.commit()
# ======================= main program =======================================
path = get_file_path('emails.csv')
read_CSV(path) # read the input file
我在做什麼?
截至目前我的數據類型爲date_of_entry
列是date
在MySQL中。
非常感謝。它確實工作.. – john
我有另一個問題[這裏](http://stackoverflow.com/questions/33196264/find-top-x-by-count-from-mysql-in-python)。看看你能幫忙嗎? – john