zoukankan      html  css  js  c++  java
  • 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(' ') #通过下标为1,提取出元祖res中的路径,并通过字符串方法split,去掉‘ ’,转换成一个一维的路径列表


    #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()

  • 相关阅读:
    【PHP】 lumen 输出sql信息
    Go学习笔记-使用MySQL数据库
    PHP检测函数是否存在
    Javascript边框闪烁提示
    【转】Ubuntu 16.04下 Mysql 5.7.17源码编译与安装
    python-mysql windows diver地址
    【转载】Python Flask 开发环境搭建(Windows)
    【转载】agentzh 的 Nginx 教程(版本 2016.07.21)
    【转载】写给新手看的Flask+uwsgi+Nginx+Ubuntu部署教程
    【转载】从零开始搭建论坛(三):Flask框架简单介绍
  • 原文地址:https://www.cnblogs.com/wangzhao2016/p/5604002.html
Copyright © 2011-2022 走看看