r/OfficeScripts • u/throwOHOHaway • Mar 07 '13
[SUBMISSION] Recursive text file find and replace
https://github.com/alouis93/txtReplace.py
7
Upvotes
r/OfficeScripts • u/throwOHOHaway • Mar 07 '13
3
u/OCHawkeye14 Mar 07 '13
Thought about this more last night and realized there was a potential for an issue in the code I posted.
If your
replaceargis shorter than yourfindarg, this could skip chunks of the document since on each subsequent pass you are beginning your search with the character that would have been the end of yourfindargstring.start = end+1should probably be changed to something else...1
u/throwOHOHaway Mar 07 '13
Original request from yesterday
1
u/[deleted] Mar 08 '13 edited Mar 09 '13
If you
import re, you can make things a little more consise:Plus you could make the
re.escapestatement optional, which would let you expose regex search as an argument flag.As an aside, can anyone tell me if there's a way to get a single read+write filehandle, where the write truncates rather than appends? I tried
r+withseek(0); truncate(0); write("stuff"), but that created some garbage at the start of the file. I'm probably misreading the docs.If you're just dealing with matching the.txtfile extention, you could just usethe string method.endswith(".txt").Actually, the stuff infnmatchmight be prettier. My solution needs the evil lambda syntax. Nice find.I'm not sure why you're wrapping lookups in
argwithstr(). AFAIK, unless you give argparse the keywordtype=intfor example, everything will already be a string. On a similar note, I'm not sure why you turn the parser object into a dict--couldn't you just use the namespace attribute notation?Here's my attempt at putting those suggestions together.
A possible next step would be to process the file line by line--at the moment, I could give this program a 16GB text file to process, and it would try to read all of that into memory.