首页 > 解决方案 > Python - 写入文本文件,但它们显示为空?

问题描述

我正在读取 .docx 文件以提取其中包含的表并将每个表重新写入 .txt 文件。我能够在终端中打印行和列并为每个表创建所有 .txt 文件,但创建的文件是空的。这是我所拥有的:

from docx import Document

document = Document('my_doc.docx')
tables = document.tables #Stores all tables in this variable
c = 1
for table in tables:
    for row in table.rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                print(paragraph.text)
                with open('table_'+str(c)+'.txt', 'w') as f:
                    f.write(paragraph.text)
    c += 1

如果我不这样做f.write(str(paragraph))f.write(paragraph.text)它只会写入存储表的位置。我究竟做错了什么?如何将表格的实际内容保存到文本文件中?谢谢!

标签: pythondocx

解决方案


您正在写入的文件不应在循环中间打开。打开的“写”模式会清除之前的任何内容。每个表只打开一个文件,因此您应该在该级别打开它。

for table in tables:
    with open('table_'+str(c)+'.txt', 'w') as f:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    print(paragraph.text)
                    f.write(paragraph.text)
    c += 1

可能可以将 放在行c += 1之前with(只是从 c=0 而不是 c=1 开始),这将有助于跟随循环 c 的递增。


推荐阅读