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 = 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()
kumaraguru.r
 
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
stranac
 
Posts: 1093
Joined: Thu Feb 07, 2013 3:42 pm


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 1 guest