如何在 word 文件文件夹中批处理此代码?

How can I batch this code on a folder of word files?

我开发了一段代码,我想 运行 在 docx 文件的文件夹中。我已经成功地弄清楚了如何在一个文件中 运行 这个(见下面的代码)但是太新手不知道如何批处理这个。

我想将所有 docx 文件写入同一个 output.txt 文件,而不是为每个 docx 文件写入单独的 txt 文件。

感谢您的帮助!

import docx

from docx import Document

def readtxtandtab(filename):
    doc = docx.Document(filename)
    fullText = []
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                fullText.append(cell.text)

    for para in doc.paragraphs:
        fullText.append(para.text)

    return '\n'.join(fullText)

with open("Output.txt", "a") as text_file:
    text_file.write(readtxtandtab('filename.docx'))

您可以使用glob 获取目录中的所有word 文件。然后您可以使用 for 循环在每个文件上执行您的代码。

import glob
.
.
.
with open("output.txt", "a") as text_file:
    for wordfile in glob.glob('*.docx'):
        text_file.write(readtxtandtab(wordfile))

对于 glob,字符串 *.docx 表示 select 以 .docx.

结尾的任何内容