【问题标题】:take lines from a .txt file and copy to a word .doc从 .txt 文件中提取行并复制到单词 .doc
【发布时间】:2013-07-08 13:24:46
【问题描述】:

我想从 .txt 文件中提取文本行并将其复制到现有 word 文档的底部。我有一些东西可以从一个文本文件到另一个文件,但总体目标是将其复制到 Word 文档的底部以进行报告。

我正在使用 python 2.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 条件时,它会打印出多次“无错误”负载,而我只需要它来打印该语句一次。

【问题讨论】:

  • 你检查过谷歌吗?谷歌将我带到这里:stackoverflow.com/questions/1035183/…,虽然问题略有不同,但它为您提供了答案。
  • 'write' 仅在多次打印时才会发生,因为它发生在每一行。此外,您正在中途关闭文件......并且在使用“with”时不需要关闭
  • 注意,写python时制表符使用4个空格。

标签: python text if-statement ms-word


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我尝试过安装模块,但没有任何乐趣,它说 docx 模块无法正常工作,但我可以看到任何想法>
    【解决方案3】:

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

    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 语句已经为您解决了这个问题。

    【讨论】:

    • @martineau:已经有处理另一部分的答案——我不太喜欢冗余。好吧,这就是我回答双重问题的结果:)
    猜你喜欢
    • 2013-06-23
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多