使用python将文本写入zipfile。如果我正在使用的代码部分执行此操作。我无法弄清楚我需要使用哪个字符来为zipfile添加新行。
if Count:
TextX = "The following species are present:"
blurb = "\r\nINSERT TABLE HERE\r\n\r\nSA* - South America\r\nNA** - North America\r\nCA*** - Central America"
else:
TextX = "No species are present."
blurb = ""
现在“if Count”为true,文档中的输出如下所示:
INSERT TABLE HERE SA* - South America NA** - North America CA*** - Central America
我希望它看起来像这样:
INSERT TABLE HERE
SA* - South America
NA** - North America
CA*** - Central America
以下是一些可能有助于排查问题的其他相关脚本代码段。脚本长达600多行,这就是我没有包含整个内容的原因。除了这件作品外,每件作品都有效。
replaceText = {"TextSpecies" : TextX,
"TEXTBLURB" : blurb}
template = zipfile.ZipFile("C:\\Template.docx")
response = zipfile.ZipFile(results, "a")
with open(template.extract("word/document.xml", databaseDir + "\\")) as tempXmlFile:
tempXml = tempXmlFile.read()
for key in replaceText.keys():
tempXml = tempXml.replace(str(key), str(replaceText.get(key)))
with open(databaseDir + "\\temp.xml", "w+") as tempXmlFile:
tempXmlFile.write(tempXml)
for file in template.filelist:
if not file.filename == "word/document.xml":
response.writestr(file.filename, template.read(file))
response.write(databaseDir + "\\temp.xml", "word/document.xml")
response.close()
template.close()
关于如何添加新行的想法?我试过\ r,\ n,\ r \ n,^ 11。没有工作。
提前致谢。
答案 0 :(得分:1)
根据您提供的详细信息,很明显您要创建Word DOCX文件。虽然docx文件是zip文件,但它是一个zip文件,其中包含非常具体的内容和针对此内容的特定规则。找到的大多数文件都是XML文件,word/document.xml
也是如此。在XML文件中,空格(包括换行符,无论它们是Unix \ n还是Windows说服\ r \ n)通常都是无关紧要的。相反,您必须创建Word期望的所有标记,并用合理的数据填充它们。
我在这里放了一个非常小的word/document.xml
文件和两个段落,所以你看到我在说什么(Word通常会将这些文件写成没有任何空格到一行,我在这里格式化它更容易读数):
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing">
<w:body>
<w:p>
<w:pPr>
<w:pStyle w:val="style0"/>
</w:pPr>
<w:r>
<w:rPr></w:rPr>
<w:t>This is the first paragraph.</w:t>
</w:r>
</w:p>
<w:p>
<w:pPr>
<w:pStyle w:val="style0"/>
</w:pPr>
<w:r>
<w:rPr></w:rPr>
<w:t>This is the second paragraph.</w:t>
</w:r>
</w:p>
<w:p>
<w:pPr>
<w:pStyle w:val="style0"/>
</w:pPr>
<w:r>
<w:rPr></w:rPr>
</w:r>
</w:p>
<w:sectPr>
<w:type w:val="nextPage"/>
<w:pgSz w:h="16838" w:w="11906"/>
<w:pgMar w:bottom="1134" w:footer="0" w:gutter="0" w:header="0" w:left="1134" w:right="1134" w:top="1134"/>
<w:pgNumType w:fmt="decimal"/>
<w:formProt w:val="false"/>
<w:textDirection w:val="lrTb"/>
</w:sectPr>
</w:body>
</w:document>
似乎每一行都是<w:p>
标签,对于新的段落,我们需要创建一个新标签,并填写所有信息。