最近项目需要将大量的压缩文件导入到数据库中,所以开始总结用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’,