最近花了点时间看了会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()
延伸:根据下面官方给出的参考资料中的数值,可以转换成多种形式多种编码文件。
参考资料: