【问题标题】:Python: Issue when trying to read and write multiple filesPython:尝试读写多个文件时出现问题
【发布时间】:2014-06-16 11:56:25
【问题描述】:

此脚本读取和写入目录中的所有单个 html 文件。该脚本重复、突出显示并写入输出。问题是,在突出显示搜索项的最后一个实例后,脚本会删除每个文件输出中最后一个搜索实例之后的所有剩余内容。任何帮助在这里表示赞赏。

import os
import sys
import re

source = raw_input("Enter the source files path:")

listfiles = os.listdir(source)

for f in listfiles:
    filepath = os.path.join(source+'\\'+f)
    infile = open(filepath, 'r+')
    source_content = infile.read()

    color = ('red')
    regex = re.compile(r"(\b in \b)|(\b be \b)|(\b by \b)|(\b user \b)|(\bmay\b)|(\bmight\b)|(\bwill\b)|(\b's\b)|(\bdon't\b)|(\bdoesn't\b)|(\bwon't\b)|(\bsupport\b)|(\bcan't\b)|(\bkill\b)|(\betc\b)|(\b NA \b)|(\bfollow\b)|(\bhang\b)|(\bbelow\b)", re.I)

    i = 0; output = ""
    for m in regex.finditer(source_content):
        output += "".join([source_content[i:m.start()],
                           "<strong><span style='color:%s'>" % color[0:],
                           source_content[m.start():m.end()],
                           "</span></strong>"])

        i = m.end()
    outfile = open(filepath, 'w')
    outfile.seek(0, 2)
    outfile.write(output)
    print "\nProcess Completed!\n"
    infile.close()
    outfile.close()


raw_input()

【问题讨论】:

    标签: python regex iterator


    【解决方案1】:

    在你的 for 循环结束后,你需要包含最后一次匹配后剩下的内容:

            ...
            i = m.end()
        output += source_content[i:])  # Here's the end of your file
        outfile = open(filepath, 'w')
        ...
    

    【讨论】:

    • 是的,我错过了。非常感谢。
    • 不客气。如果这解决了您的问题,请考虑将此答案标记为“已接受”,以便将来的用户可以看到它对您有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多