#Open the database connection db = MySQLdb.connect(host='localhost',user='bob',passwd='talent',db='top_ten',port=3306, charset='utf8')
#Automatic submission db.autocommit(True)
#Gets the operation cursor cursor = db.cursor()
with open('access_log-20170217', 'r') as f: res = {} #Get ip, url, status for line in f.readlines(): line = line.split(' ') ip = line[0] url = line[6] status = line[8] #print ip, url, status #ip, url, status as key, each time plus 1 res[(ip, url, status)] = res.get((ip, url, status),0)+1 #Generate a list res_list = [(k[0],k[1],k[2],v) for k,v in res.iteritems()] # Print the top ten lines #for k in sorted(res_list,key=lambda x:x[3],reverse=True)[:10]: #print k
#SQL statement inserted for i in res_list: #print i sql = "insert into log(ip, url, status, total) values('%s', '%s', '%s', '%s')" %(i[0], i[1], i[2], i[3])
try: #Execute the SQL statement cursor.execute(sql)