从.txt文件中提取行并复制到word.d

2024-05-16 07:53:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从.txt文件中提取几行文本,并将其复制到现有word文档的底部。我有一些方法可以从一个文本文件复制到另一个文本文件,但总体目标是将其复制到word文档的底部,以便生成报表。在

我正在使用Python2.6,目前

with open('Error.txt', 'w') as f1:
    for line in open('2_axis_histogram.txt'):
        if line.startswith('Error'):
            f1.write(line)
        else:
            f1.write("No Error ")
    f1.close()

我不知道怎么才能把这句话转化成word。在

另外,当没有错误并且使用else条件时,它会打印多次“no error”加载,而我只需要它打印一次该语句。在


Tags: 文件方法文档文本txt报表lineerror
3条回答

第一个问题:使用Google或StackOverflow搜索:Reading/Writing MS Word files in Python

第二个问题:让你的“无错误”显示器退出循环。。。在

要除去无关的"No Error"消息,请将else语句放入for循环中,而不是{}中,因为每行都会检查后者:

with open('Error.txt', 'w') as f1:
    for line in open('2_axis_histogram.txt'):
        if line.startswith('Error'):
            f1.write(line)
            break            # Exit the for loop, bypassing the else statement
    else:                    # Only executed if the for loop finishes
        f1.write("No Error ")           

另外,不需要关闭f1-with语句已经为您处理好了。在

你应该看看https://github.com/mikemaccana/python-docx

这是一个创建、读取和写入Microsoft Office Word 2007 docx文件的模块。在

相关问题 更多 >