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

  • 相关阅读:
    如何打日志才能方便排查问题?
    为什么 HashMap 并发时会引起死循环?
    Spring 为什么会有 FactoryBean?
    常用 Git 使用技巧,收藏了~
    Gin中context的使用
    Gin的路由算法
    k8s中的网络通信总结
    k8s架构
    Golang中的值拷贝与引用拷贝
    golang知识要点总结
  • 原文地址:https://www.cnblogs.com/wangzhao2016/p/5604002.html
Copyright © 2011-2022 走看看