Issue when trying to read and write multiple files

This is the place for queries that don't fit in any of the other categories.

Issue when trying to read and write multiple files

Postby kumaraguru.r » Mon Jun 16, 2014 5:41 am

This script reads and writes all the individual html files in a directory. The script reiterates, highlight and write the output.The issue is, after highlighting the last instance of the search item, the script removes all the remaining contents after the last search instance in the output of each file. Any help here is appreciated.

Here is the code:

Code: Select all
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 =
    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:],

        i = m.end()
    outfile = open(filepath, 'w'), 2)
    print "\nProcess Completed!\n"

Posts: 1
Joined: Mon Jun 16, 2014 5:35 am

Re: Issue when trying to read and write multiple files

Postby stranac » Mon Jun 16, 2014 9:39 am

Opening a file in write mode ('w') deletes the contents of the file.
To avoid this, you can either open it in append mode ('a'), or only open the file once, outside of the loop.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
Posts: 1592
Joined: Thu Feb 07, 2013 3:42 pm

Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 3 guests