python写入文件到docx_从python中的txt文件写入docx文件

本文介绍如何使用Python将txt文件中的数据填充到docx文件中。通过读取txt文件,替换docx文档的XML内容,然后创建新的docx文件。在尝试过程中遇到文件无法打开的编码问题。
摘要由CSDN通过智能技术生成

我一直在尝试使用python代码来填充word中的表单,这些数据是我从互联网上获取的。我将数据写入txt文件,现在正试图用以下代码填充word文件:import zipfile

import os

import tempfile

import shutil

import codecs

def getXml(docxFilename,ReplaceText):

zip = zipfile.ZipFile(open(docxFilename,"rb"))

xmlString= zip.read("word/document.xml")

for key in ReplaceText.keys():

xmlString = xmlString.replace(str(key), str(ReplaceText.get(key)))

return xmlString

def createNewDocx(originalDocx,xmlString,newFilename):

tmpDir = tempfile.mkdtemp()

zip = zipfile.ZipFile(open(originalDocx,"rb"))

zip.extractall(tmpDir)

#3tmpDir=tmpDir.decode("utf-8")

with open(os.path.join(tmpDir,"word/document.xml"),"w") as f:

f.write(xmlString)

filenames = zip.namelist()

zipCopyFilename = newFilename

with zipfile.ZipFile(zipCopyFilename,"w") as docx:

for filename in filenames:

docx.write(os.path.join(tmpDir,filename),filename)

shutil.rmtree(tmpDir)

f=open('test.txt', 'r',)

text=f.read().split("\n")

print text[1]

Pavarde = text[1]

Replace = {"PAVARDE1":Pavarde}

createNewDocx("test.docx",getXml("test.docx",Replace),"test2.docx")

文件已创建,但我无法打开它。在

我得到以下错误:

^{pr2}$

我的猜测是编码有问题,但我找不到解决方案。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值