Python - 操作 doc / docx

文章目录

    • 读取 docx
    • 读取 doc


注意:doc/docx 文件名中如果包含空格,可能导致读取失败,可以提前替换为 _


读取 docx

textract 和 docx2txt 两个库都支持读取 docx

import textract
import docx2txt

file_path = '.../docx/a.docx'
print('file_path : ', file_path)
bs = textract.process(file_path)  # 得到的是 bytes
text1 = bs.decode('utf-8')

text2 = docx2txt.process(file_path)


读取 doc

安装 antiword
参考:https://blog.csdn.net/Webben/article/details/103343828


def test2():

    root_dir = '../doc/'
    txt_dir = root_dir + 'txt/'

    command_path = '/home/xx/software/antiword-0.37/antiword'

    for file_name in os.listdir(root_dir):

        file_id = file_name.replace('.doc', '')
        print('\n-- ', file_id)

        doc_path = root_dir + file_name
        txt_path = txt_dir + file_id + '.txt'
 
        script = f'{command_path} -f {doc_path} > {txt_path} '
        try:
            ret = os.system(script) 
        except Exception as err:
            print('xx error : ', file_name)
            continue



你可能感兴趣的:(Python,python,开发语言,后端,antiword)