使用Python将.doc文件转成.docx遍历列表循环打开.docx文件提取图片,将图片存储到本地,将名称存储到postgresql数据库中

1.将word.doc文件转成word.docx文件

import os
from win32com import client as wc

file_path = r"D:\ChenKunMingWorkInformation\9.3.3无锡市古树名木资源普查统计表(2020)\9.3.3无锡市古树名木资源普查统计表(2020)"
for i in os.listdir(file_path):
    for j in os.listdir(file_path+"/"+i):
        print(j)
        word = wc.Dispatch("Word.Application")
        doc = word.Documents.Open(file_path+"/"+i+"/"+j)
        doc.SaveAs(r"D:\ChenKunMingWorkInformation\docx"+j.split(".")[0]+".docx",12)

2.循环打开.docx文件提取图片并存储

import os
import random
import re
import time
import psycopg2
from docx import Document

# 获取当前时间戳
timestamp = int(time.time())

# 保存图片路径
result_path = r"C:\Users\CHENKUNMING\Documents\image"
# 打开的docx
file_path = r"C:\Users\CHENKUNMING\Documents"
# 循环文件列表获取文件名
for i in os.listdir(file_path):
    # 获取有关.docx结尾文件并且排除掉~$的文件
    if ".docx" in i and "~$" not in i:
        print(i)
        # 文件名以.截取取前部分
        name = i.split(".")[0]
        # 根据前部分获取数字编号
        bh = re.findall(r'\d+', name)[0]
        # 打开docx文件
        doc = Document(file_path + "\\" + i)
        dict_rel = doc.part._rels
        for rel in dict_rel:
            rel = dict_rel[rel]
            if "image" in rel.target_ref:
                # 生成文件名
                img_name = ''.join(random.choices('0123456789', k=10))
                img_name_date = str(timestamp) + "-" + img_name + ".png"
                # 判断 文件夹是否存在 如果不存在 则:
                if not os.path.exists(result_path):
                    os.makedirs(result_path)
                    word_name = os.path.splitext("word_path")[0]
                    with open(f'{result_path}/{img_name_date}', "wb") as f:
                        # 写入
                        f.write(rel.target_part.blob)
                else:
                    with open(f'{result_path}/{img_name_date}', "wb") as f:
                        f.write(rel.target_part.blob)

                # update postgresql image name
                conn = psycopg2.connect(
                    host="127.0.0.1",
                    database="test",
                    user="root",
                    password="123456"
                )
                with conn.cursor() as cursor:
                    cursor.execute("update gsmm set photo = %s where gsbh = %s", (img_name_date, bh))
                    conn.commit()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

令人作呕的溏心蛋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值