File Search and Replace

This forum allows you to share scripts with other Zeus users. Please do not post bug reports, feature requests or questions to this forum, but rather use it exclusively for posting scripts or for the discussion of scripts that have been posted.
Post Reply
Site Admin
Posts: 2547
Joined: Fri Aug 13, 2004 5:10 pm

File Search and Replace

Post by jussij »

The following Zeus Python macro will do a regular expression search and replace operation over the entire contents of a text file.

Code: Select all

import re
import os.path
import zeus

# Python Help:

def file_text_replace(input_file_name, find_text, replace_text):

    # read the entire fileinto memory
    file_data = open(input_file_name).read()

    if, file_data):
        backup_file_name = input_file_name + ".bak"

        if os.path.exists(backup_file_name):

        os.rename(input_file_name, backup_file_name)

        o = open(input_file_name, "w")

        o.write(re.sub(find_text, replace_text, file_data))
        return 1

    return 0

def key_macro():
    # ask for a user provide the alignment character
    find_text, replace_text = zeus.user_input("Find:", "", "Replace:", "")

    if (len(find_text) > 0) and (len(replace_text) > 0):
        # make sure this file exists
        input_file_name = "c:\\temp\\test.txt"

        # helpful for debugging
        #zeus.message_box(0, "input_file_name: '" + input_file_name + "'\nfind_text: '" + find_text + "'\nreplace_text: '" + replace_text + "'")

        # do the search and replace
        # c:\\temp\\test.txt.bak
        if file_text_replace(input_file_name, find_text, replace_text) > 0:
            zeus.message("The changes where made to the '" + input_file_name + "' file.")
            zeus.message("The find text '" + find_text + "' was not found in the'" + input_file_name + "' file.")

        zeus.message("Operation cancelled by user.")

key_macro() # run the macro
Post Reply