0

I have two open source files I've been messing around with, one file is a small macro script I'm working with, second is a txt file filled with commands I'd like to insert in to the first script in a random order within their respective lines. I've managed to come up with this script for searching and replacing the values, but not to insert them in a random order from the second txt file.

def replaceAll(file,searchExp,replaceExp):
    for line in fileinput.input(file, inplace=1):
        if searchExp in line:
            line = line.replace(searchExp,replaceExp)
        sys.stdout.write(line)

replaceAll('C:/Users/USERACCOUNT/test/test.js','InterSearchHere', RandomValueFrom2ndTXT)

Any help if greatly appreciated! Thanks in advance!

1 Answer 1

1
import random
import itertools as it

def replaceAll(file,searchExp,replaceExps):
    for line in fileinput.input(file, inplace=1):
        if searchExp in line:
            line = line.replace(searchExp,next(replaceExps))
        sys.stdout.write(line)

with open('SecondFile','r') as f:
    replaceExp=f.read().splitlines()
random.shuffle(replaceExps)         # randomize the order of the commands
replaceExps=it.cycle(replaceExps)   # so you can call `next(replaceExps)`

replaceAll('C:/Users/USERACCOUNT/test/test.js','InterSearchHere', replaceExps)

Each time you call next(replaceExps) you get a different line from the second file.

When a finite iterator is exhausted, next(replaceExps) will raise a StopIteration exception. To prevent that from ever happening, I used itertools.cycle to make the shuffled command list repeat ad infinitum.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.