1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import os import csv import pymysql conn=pymysql.connect(host='xx.xx.xx.xx',port=3306,user='root',password='password',db='weibo',charset='utf8mb4') cursor=conn.cursor() for root,dirs,files in os.walk(r"E:\"): #遍历目录 for f in files: if f.split(".")[-1] == "csv": user_id=f.split(".")[0] csv_file=open(os.path.join(root,f),"r",encoding='utf-8') csv_reader=csv.reader(csv_file) csv_comment=list(csv_reader) # print("test") for t in csv_comment: if t[0].find("微博id") > -1: continue insert="INSERT INTO `weibo` (`id`, `user_id`, `content`, `article_url`, `original_pictures`, `retweet_pictures`, `original`, `video_url`, `publish_place`, `publish_time`, `publish_tool`, `up_num`, `retweet_num`, `comment_num`) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}','{10}', '{11}', '{12}', '{13}');".format(t[0],user_id,t[1],t[2],t[3],"NULL","1",t[4],t[5],t[6],t[7],t[8],t[9],t[10]) #对应的插入语句 try: cursor.execute(insert) conn.commit() print("成功") except: print("失败")
|