Python - 写入文本文件,但它们显示为空?
Python - Writing to text files, but they show up empty?
我正在读取一个 .docx 文件以提取其中的 table 并将每个 table 重新写入一个 .txt 文件。我能够在终端中打印行和列,并为每个 table 创建所有 .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)
,它只会写入 table 的存储位置。我究竟做错了什么?如何将 tables 的实际内容保存到文本文件中?
谢谢!
问题是您每次通过 for 循环时都会打开文件,如下所示:
with open('table_'+str(c)+'.txt', 'w') as f:
这会打开文件进行写入,但也会清除文件中的所有现有文本,这可能就是您的文件为空的原因。
要解决此问题,您可以使用 'a'
而不是 'w'
,从而附加到文件而不是重新写入。
您正在写入的文件不应在循环中间打开。打开的“w”rite 模式会清除所有以前的内容。每个 table 您只能打开一个文件,因此您应该在该级别打开它。
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 递增。
我正在读取一个 .docx 文件以提取其中的 table 并将每个 table 重新写入一个 .txt 文件。我能够在终端中打印行和列,并为每个 table 创建所有 .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)
,它只会写入 table 的存储位置。我究竟做错了什么?如何将 tables 的实际内容保存到文本文件中?
谢谢!
问题是您每次通过 for 循环时都会打开文件,如下所示:
with open('table_'+str(c)+'.txt', 'w') as f:
这会打开文件进行写入,但也会清除文件中的所有现有文本,这可能就是您的文件为空的原因。
要解决此问题,您可以使用 'a'
而不是 'w'
,从而附加到文件而不是重新写入。
您正在写入的文件不应在循环中间打开。打开的“w”rite 模式会清除所有以前的内容。每个 table 您只能打开一个文件,因此您应该在该级别打开它。
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 递增。