Find and Replace via PythonScript on subfolders
-
NPP Find & Replace doesn’t support mathematical operations and recommends(?) doing it using a PythonScript plugin. Fair enough, I went and got myself the script:
def multiply2(m): return 'Mass="' + str(float(m.group(1)) * 2) + '"' editor.rereplace('Mass="([0-9]+(?:\.[0-9]+)?)"', multiply2);
I tested it, it works, I’m happy. Unfortunately, I need to run this script on over 1700 files in like 100 different subfolders and I’m stumped. For some reason I thought it would be as easy as opening the main folder as a Workspace but that was perhaps a bit too optimistic.
-
You would have to program a loop around the
editor.rereplace
where you have PythonScript open a file, run theeditor.rereplace
, save, and close, then move on to next file.Since you have 100 directories with a total of 1700 files, you would have to probably have a double-nested loop, with the first loop going over the directories, and the second loop going over the files in each directory.
That looping portion is a generic Python coding question, and isn’t specific to Notepad++ or the PythonScript plugin (ie, the answer doesn’t change if you’re using python.exe instead of using Notepad++ and the PythonScript plugin), so you can search the internet for general Python-language help on how to write loops in Python that loop over all (matching) files in all (matching) directories.
-
In addition to what Peter said, inside your loop you would call
notepad.open()
, then do your replacement(s), then callnotepad.close()
.