【发布时间】:2019-03-14 03:03:44
【问题描述】:
我编写了以下代码来将我的 docx 文件转换为文本文件。我在文本文件中打印的输出是整个文件的最后一段/部分,而不是完整的内容。代码如下:
from docx import Document
import io
import shutil
def convertDocxToText(path):
for d in os.listdir(path):
fileExtension=d.split(".")[-1]
if fileExtension =="docx":
docxFilename = path + d
print(docxFilename)
document = Document(docxFilename)
# for printing the complete document
print('\nThe whole content of the document:->>>\n')
for para in document.paragraphs:
textFilename = path + d.split(".")[0] + ".txt"
with io.open(textFilename,"w", encoding="utf-8") as textFile:
#textFile.write(unicode(para.text))
x=unicode(para.text)
print(x) //the complete content gets printed by this line
textFile.write((x)) #after writing the content to text file only last paragraph is copied.
#textFile.write(para.text)
path= "/home/python/resumes/"
convertDocxToText(path)
【问题讨论】:
-
with io.open(textFilename,"w", encoding="utf-8") as textFile:在你的for para in document.paragraphs:循环。这意味着您在每次迭代中以写入模式继续打开文件,擦除任何现有内容。您需要在运行循环之前打开文件一次,即将for循环放在with块内,而不是相反。 -
感谢我进行了更改,并且成功了..
-
@sharayusalunkhe 这个代码目前对你有用吗?,即使更正了,我的代码也会出错,,,
标签: python file-conversion python-docx