python 执行mysql文件路径_Python调用MYSQL,将文件名和路径批量入库用法小结

最近项目需要将大量的压缩文件导入到数据库中,所以开始总结用Python批量处理的办法,本次是首先将这些压缩文件的文件名提取出来,然后导入到数据库中。

由于涉及到路径的读取处理,所以方法有os模块和commands模块,本次主要采用commands模块(有时间的话,一定要再探索一下os模块实现的方式)。

# encoding: utf-8

#!/usr/bin/python

import commands

import MySQLdb

conn = MySQLdb.connect(

host=‘localhost‘,

user=‘***‘,

passwd=‘***‘,

db=‘***‘,

charset=‘utf8‘)

cur = conn.cursor()

#path = ‘/home/***/***/‘

res = commands.getstatusoutput(‘find/home/***/***/企业名录/‘ ) #res 为返回的元组,包含(status,pathlist)即状态码,路径两个元素;find为Linux下查找文件的命令

#res = commands.getstatusoutput(‘find /home/***/***/‘ )

pathlist = res[1].split(‘\n‘) #通过下标为1,提取出元祖res中的路径,并通过字符串方法split,去掉‘\n’,转换成一个一维的路径列表

#for line in pathlist:

#type(line)

for i in range(0,len(pathlist)): #通过for循环将列表中的文件路径取出

fileLine = pathlist[i] #取出后的文件路径为一个字符串

#print type(fileLine)

seperator = fileLine.rfind(‘/‘) #通过字符串方法rfind,找到字符‘/’在路径中最后出现的位置,在此位置之前为路径,在此之后为文件名(但是有一个小问题是文件夹的名字是一个路径)

filePath = fileLine[0:seperator+1] #通过切片的方式提取出文件路径

fileName = fileLine[seperator+1:] #通过切片的方式提取出文件名

fileType = fileLine[-3:]

#sql = "insert into table rarFileList(ID,filePath,fileName,fileType) values (%s,%s,%s,%s)"(str(i),filePath,fileName,fileType)

#sql = "insert into table rarFileList(ID,filePath,fileName,fileType) values (" + str(i) + "," + filePath + "," + fileName + "," + fileType + ")"  #此处为多种方式尝试,需要小心会有一些数据类型错误等情况出现

#print sql

#cur.execute(sql)

cur.execute("insert into rarFileList(ID,filePath,fileName,fileType) values (%s,%s,%s,%s)",(i,filePath,fileName,fileType))

#if fileLine[-3:] == ‘rar‘:

#sql = "update rarFileList set status= ‘done‘ where fileType = ‘rar‘"

#cur.execute(sql)

#elif fileLine[-3:]== ‘zip‘:

#sql = "update rarFileList set status= ‘done‘ where fileType =‘zip‘"

#cur.execute(sql)

cur.close()

conn.commit()

conn.close()

原文:http://www.cnblogs.com/wangzhao2016/p/5604002.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值