Python:尝试读取和写入多个文件时出现问题

Python:尝试读取和写入多个文件时出现问题,python,regex,iterator,Python,Regex,Iterator,此脚本读取和写入目录中的所有单个html文件。脚本重复、突出显示并写入输出。问题是,在突出显示搜索项的最后一个实例后,脚本将删除每个文件输出中最后一个搜索实例之后的所有剩余内容。这里的任何帮助都是感激的 import os import sys import re source = raw_input("Enter the source files path:") listfiles = os.listdir(source) for f in listfiles: filepath

此脚本读取和写入目录中的所有单个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()
导入操作系统
导入系统
进口稀土
source=原始输入(“输入源文件路径:”)
listfiles=os.listdir(源)
对于列表文件中的f:
filepath=os.path.join(source+'\\'+f)
infle=open(文件路径“r+”)
source_content=infle.read()
颜色=(‘红色’)
(b b b b);(b b b b b);;(b b b b b b b b b b);(b b b b b b b用户\b b);,(b b b b b用户\b b);;(b b b\BMY\b);;(b\b b b)重新.重新编译(r)重重.编译(r)(r)编译(r)(r)(r)(r)(r)(r)(r)(b b b\b\b b b b b\b b b b b b\b b b b\b b b\b b b\b b b\b b b b\b b b b b b\b b b b b b b b)目前目前,;;(b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b b bebebebebebebebebebebebebebebebebebebebebebebeb)目前,,;(b b b b b b)(\bhang\b)|(\bblow\b)”,re.I)
i=0;output=“”
对于regex.finditer中的m(源内容):
输出+=“”.join([source\u content[i:m.start()],
“”颜色[0:],
源内容[m.开始():m.结束(),
“”])
i=m.end()
outfile=open(文件路径“w”)
外文件寻道(0,2)
outfile.write(输出)
打印“\n进程已完成!\n”
infle.close()
outfile.close()
原始输入()

for循环结束后,需要包括上次匹配后剩下的内容:

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

是的,我错过了。非常感谢,不客气。如果这解决了你的问题,考虑把这个答案标记为“接受”,这样将来的用户可以看到它对你有用。