查询数据库信息,匹配数据,并且复制图片到指定文件夹

#实现功能:在对方数据库中查询name,mortgage_infos,mortgage_contract信息,
# 匹配后两者中的图片数据,根据匹配得到路径信息在本机指定路径当中查找对应图片,
# 根据name创建文件夹
# 把找到的图片保存在新创建与数据库管联的目录下

import os,shutil,pymysql,re
def mkdir(path):
    # 去除首位空格
    path = path.strip()
    # # 去除尾部 \ 符号
    path = path.rstrip("\\")
    # 判断路径是否存在
    # 判断结果
    isExists = os.path.exists(path)

    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path)
        print(path + ' 创建成功')
        return True
    else:
        # 如果目录存在则创建加(2),并提示目录已存在
        i=1
        while True:
            isExists = os.path.exists(path)
            if isExists:
                i += 1
                path += str(i)
            else:
                os.makedirs(path)
                print(path + ' 创建成功')
                break
        # os.makedirs(path)
        print(path + ' 目录已存在改名')
                # break
        return True
# 定义要创建的目录
def validateTitle(title):
    rstr = r"[\/\\\:\*\?\"\<\>\|]"  # '/ \ : * ? " < > |'
    new_title = re.sub(rstr, "_", title)  # 替换为下划线
    return new_title

def main(target_dir_path):
    # 创建connection链接
    conn = pymysql.connect(host="对方ip",port=端口,database=名称,user="***",password="***",charset="utf8")
    # 获取游标Cursor对象
    cur = conn.cursor()
    count=cur.execute("select name,mortgage_infos,mortgage_contract from fanwe_deal")
    print(count)
    datas = cur.fetchall()
    for data in datas:
        ret=re.findall(r'public/(.*?)"', str(data))
        target_name = data[0]
        target_name = validateTitle(target_name)
        # target_name = target_name.replace('/', '\\')
        target_path = target_dir_path + '\\' + 'pic\\' + target_name
        mkdir(target_path)
        if ret:
            for path in ret:
                #获取在数据库中截取的单个图片路径
                # file_path=os.getcwd() + '\\' + path
                file_path=target_dir_path + '\\' + path
                #这个图片路径拼接成绝对路径 F:\****\attachment/201709/22/16/59c4ca777085c.JPG
                # 切割路径获取文件夹目录,文件名
                res=os.path.split(file_path)
                file_dir_path=res[0]#F:\*******\attachment/201709/22/16
                pic_name=res[1]#59c4ca777085c.JPG
                #判断该路径是否存在
                if os.path.exists(file_dir_path):
                    files_list = os.listdir(file_dir_path)
                    # 如果图片存在查找的目录下,判断图片是否在pic_files下,
                    # 如果不存在,复制该图片到当前路径下的新创建的pic_files目录下
                    if pic_name in files_list:
                        if pic_name not in os.listdir(target_path):
                            try:
                                shutil.copy(file_path, target_path)#复制文件到指定路径目录下
                            except :
                                pass
    conn.commit()
    cur.close()
    conn.close()
if __name__ == "__main__":
    target_dir_path='D:\****
    main(target_dir_path)

猜你喜欢

转载自blog.csdn.net/weixin_42989364/article/details/88887539