#!/usr/bin/env python # -*- coding:utf-8 -*- #导入正则模块 import re #导入os模块,本例用它来做文件写入操作 import os #导入日志模块 import logging import logging.handlers import xlwt import xlrd import MySQLdb import pymysql db = pymysql.connect("localhost","root","123456","my_db_hanchuan01" ) # 遍历文件+采集手机号的方法 def count(dirname='D:/tmp/临时数据源/sheet转换/txtfiles'): #-----------------------正则-------------------------------- #手机号正则 pattern_mob = re.compile('1[345789]\d{9}') # pattern_mob_plus = re.sub('1[345789]\d{9}','1[345789]\d{9}+123') #---------------------统计文件------------------------------ # 记录文件总数的变量 count=0 num=0 # 记录含手机号文件数的变量 for root, dirs, files in os.walk(dirname): # 得到每个文件夹下文件数量 for filename in files: # 将文件名与路径拼接成全路径 f = open(dirname+'/'+filename,'r+', encoding='utf-8') var1 = (filename) # 将文件名写入数据库 result = pattern_mob.findall(f.read()) # result = pattern_mob_plus.findall(f.read()) # result = pattern_mob.findall # result = result+"123" for phonenames in result: var2 = (phonenames) print(var1) print(var2) cursor = db.cursor() # 使用 cursor() 方法创建一个游标对象 cursor cursor.execute("INSERT INTO 00_HEFEI_PHONES VALUES('%s', %s)" % (var1,var2)) # 执行sql语句 db.commit() # 主函数 if __name__ == '__main__': # # 调用count()h函数 count() db.close()