Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将文本文件附加到word文档Python docx中_Python_Python Docx - Fatal编程技术网

将文本文件附加到word文档Python docx中

将文本文件附加到word文档Python docx中,python,python-docx,Python,Python Docx,我正在学习python docxpython模块 我不知道如何将.txt文件附加到word文档中并保存它 我能够将文件内容写入如下单词中 from docx import Document document = Document() with open('textfile.txt') as f: for line in f: document.add_paragraph(line) document.save('wordfile.docx') 但是我想附加.txt文件,

我正在学习python docxpython模块

我不知道如何将
.txt
文件附加到word文档中并保存它

我能够将文件内容写入如下单词中

from docx import Document
document = Document()
with open('textfile.txt') as f:
    for line in f:
        document.add_paragraph(line)
document.save('wordfile.docx')
但是我想附加
.txt
文件,而不是将内容写入word

预期产出:


有人能帮我做这件事吗?

这段代码是通过Word(VBA)本身完成的:


这项工作将是确保安装了Office Interop(我没有,所以无法测试)并将脚本重写为Python,这是某人执行类似操作的示例:

此代码从Word(VBA)本身执行任务:


这项工作将是确保您安装了Office Interop工具(我没有,所以无法测试),并将脚本重写为Python,这里有一个类似的例子:

请解释,您是在询问如何使用Python打开文件还是如何附加到文件?我正在尝试使用Python生成word文档,并希望将textfile附加到word文档中。请检查当您说“附加”时,您的意思是实际将文件作为附件添加到word文档,还是将其内容添加到文档末尾?(因为您可以使用文本文件进行任何操作)
python docx
第三方库似乎不支持添加附件,就像您可以从VBA中添加附件一样,因此您可能需要研究使用其他库或工具进行此操作的方法。@Grismar您能提出任何方法,这对我们有帮助吗:-)请解释,您是在询问如何使用Python打开文件还是如何附加到文件?我正在尝试使用Python生成word文档,并希望将textfile附加到word文档中。请检查当您说“附加”时,您的意思是实际将文件作为附件添加到word文档,还是将其内容添加到文档末尾?(因为您可以使用文本文件进行任何操作)
python docx
第三方库似乎不支持添加附件,就像您可以从VBA中添加附件一样,因此您可能需要研究使用其他库或工具来实现这一点的方法。@Grismar您能建议任何方法,这对我们有帮助:-)
Public Function RetrieveOLEInfo(fileExt As String)
    Dim regKey As String
    Dim oleServer As String

    fileExt = "txt"
    regKey = "HKEY_Classes_Root\."
    RetrieveOLEInfo = System.PrivateProfileString("", regKey & fileExt, "")
End Function
Sub Test()
    Documents.Add
    ActiveDocument.InlineShapes.AddOLEObject _
        ClassType:=RetrieveOLEInfo("txt"), FileName:="c:\0000\test.txt", LinkToFile:=True, _
        DisplayAsIcon:=True, IconLabel:="test.txt"
End Sub