python声明编码格式_使用python将doc文件转为utf8编码格式的txt

本文介绍了如何使用Python结合win32com模块批量将DOC和DOCX文档转换为TXT格式。通过遍历指定文件夹,对符合筛选条件的文件进行操作,利用Microsoft Word API进行文件转换,并提供了官方参考资料链接,以便转换不同编码的文件。
摘要由CSDN通过智能技术生成

最近花了点时间看了会doc的转换,果然官方文档最好用,代码如下:

import os

import sys

import fnmatch

import win32com.client

PATH = os.path.abspath(os.path.dirname(sys.argv[0]))

doc_path = PATH + ‘/data/doc/’

txt_path = PATH + ‘/data/txt/’

def convert_dir_to_txt():

“””

将默认整个文件夹下的文件都进行转换

:return:

“””

for root, dirs, files in os.walk(doc_path):

for _dir in dirs:

pass

for _file in files:

if fnmatch.fnmatch(_file, ‘*.doc’):

store_file = txt_path + _file[:-3] + ‘txt’

elif fnmatch.fnmatch(_file, ‘*.docx’):

store_file = txt_path + _file[:-4] + ‘txt’

word_file = os.path.join(root, _file)

dealer.Documents.Open(word_file)

try:

dealer.ActiveDocument.SaveAs(store_file, FileFormat=7,Encoding=65001)

except Exception as e:

print(e)

dealer.ActiveDocument.Close()

dealer = win32com.client.gencache.EnsureDispatch(‘Word.Application’)

convert_dir_to_txt()

延伸:根据下面官方给出的参考资料中的数值,可以转换成多种形式多种编码文件。

参考资料:

https://docs.microsoft.com/zh-cn/office/vba/api/Office.MsoEncoding

https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2010/ff839952(v=office.14)?redirectedfrom=MSDN

————————————————

版权声明:本文为CSDN博主「六神就是我」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/sinat_33455447/java/article/details/101020285

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值