python - 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)
它只会写入存储表的位置。我究竟做错了什么?如何将表格的实际内容保存到文本文件中?谢谢!
解决方案
您正在写入的文件不应在循环中间打开。打开的“写”模式会清除之前的任何内容。每个表只打开一个文件,因此您应该在该级别打开它。
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 的递增。
推荐阅读
- reactjs - TypeError:无法读取 reactjs 和 laravel 应用程序中未定义的属性“pbrd_display_name”
- python - 使用 Python 的 SQL Server 2012 连接错误
- google-sheets - GoogleSheets 中的 If And Then 公式是否有限制?
- firebase - Firebase 代理(反向代理)
- powerbi - PowerBI - 困扰我的问题;测量在不同层次结构级别上正确汇总,但使用切片器在表中消失名称
- visual-studio-code - VS Code 终端为空白/不可用
- python - 使用 for 循环将 Pandas 系列转换为 Dataframe
- html - 中心表单输入但不是标签
- r - 优化 R(投资组合)中的权重
- sql - 尝试添加 ROW_NUMBER 时是否可以在此查询中删除级联 CTE