有没有办法以编程方式将文本从一个word文件添加到另一个word文件?

时间:2018-01-18 15:21:25

标签: python ms-word

我尝试在MS Word字段上使用python的mailmerge库,但是我丢失了文本上的所有格式。我想知道是否有办法在Word中复制并使用'插入>对象>文件来自文件'使用python库(或者此时的任何东西)。如果有一个简单的方法可以通过编辑oxml来实现这一点,即使这样也行。我只是想知道从哪里开始寻找,或者我是否需要手动编程。

1 个答案:

答案 0 :(得分:0)

我试着想出一些东西,希望它有用。在下面的代码中,我打开文件或创建一个文件,如果它不存在,写一些数据行。在file1中读取相同的数据行,然后将它们写入新创建的文件中。

#Read and write files using the built-in Python methods
def main():
    #open the file for writing and create if it does not exist
    file = open("file1.txt", "w+")
    #write some lines of data to the file
    for i in range(5):
        file.write("This is Andela %d\r\n" % (i + 1))
    file.close()
    #write text in file1.txt to another file called file2
    open("file2.txt", "w").writelines([l for l in open("file1.txt").readlines() if "Andela" in l])

main()