python怎么编辑文件_使用python编辑.odt文件

本文介绍了如何使用ezodf库创建并编辑ODT文件,通过zipfile处理content.xml,实现了动态替换和重新打包的过程。重点在于分享defthingy函数,展示了如何处理XML内容并更新压缩文件。
摘要由CSDN通过智能技术生成

嗯,我想通了。完成该计划。我使用ezodf来创建文件,然后使用zipfile来提取和编辑content.xml,然后通过一个很好的> def thingy <从here重新打包整个东西。我试图弄脏etree ......但我无法弄清楚......

from ezodf import newdoc

import os

import zipfile

import tempfile

for s in temp2:

input2 = s

input2 = str(s)

input1 = cname[0]

file1 = '.odt'

namef = input2 + input1 + file1

odt = newdoc(doctype='odt', filename=namef, template='template.odt')

odt.save()

a = zipfile.ZipFile('template.odt')

content = a.read('content.xml')

content = str(content.decode(encoding='utf8'))

content = str.replace(content,"XXDATEXX", input2)

content = str.replace(content, 'XXNAMEXX', input1)

def updateZip(zipname, filename, data):

# generate a temp file

tmpfd, tmpname = tempfile.mkstemp(dir=os.path.dirname(zipname))

os.close(tmpfd)

# create a temp copy of the archive without filename

with zipfile.ZipFile(zipname, 'r') as zin:

with zipfile.ZipFile(tmpname, 'w') as zout:

zout.comment = zin.comment # preserve the comment

for item in zin.infolist():

if item.filename != filename:

zout.writestr(item, zin.read(item.filename))

# replace with the temp archive

os.remove(zipname)

os.rename(tmpname, zipname)

# now add filename with its new data

with zipfile.ZipFile(zipname, mode='a', compression=zipfile.ZIP_DEFLATED) as zf:

zf.writestr(filename, data)

updateZip(namef, 'content.xml', content)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值