Hi all!
(TL;DR - How can I use python 3 in a .nim file?)
I recently set out to write a program to edit a large text file of ~400,000 lines. The program needed to replace strings in that file that matched any lines in another file, and it had to reference a third large file for the replacement text. It was also important to me that the program executed quickly, in around 3 minutes or less.
Although I ended up using just Nim and a little bash, I spent an hour or two trying to outsource the edit-in-place to Python, with no luck. I grabbed a snippet of Python 3 from stackoverflow and spent a while trying to get it to work with nimpy, Pythonize, and the Python3 nim library. The latter two libraries seem to need some updating -- they both throw pragma errors, even with their GitHub example code. Nimpy, on the other hand, seems to work just fine, but the documentation is difficult for my brain to comprehend for this purpose.
stackoverflow Python script:
import in_place with in_place.InPlace('data.txt') as file: for line in file: line = line.replace('test', 'testZ') file.write(line)
How would I go about using this in a Nim script? It seems like there's a lot of documentation and libraries for using Nim in Python, but vice-versa is a little tougher. All of this would have been so much easier if there were a way for Nim to modify the current line during "for line in..." loops, like in the Python example's "line = line.replace()" usage. Did I miss an easy standard or 3rd-party way of doing this?
Thanks!
Warning, untested code:
include prelude
proc main(source, tmp: string) =
var f = open(tmp, fmWrite)
try:
for line in lines(source):
f.writeLine line.replace("test", "testZ")
finally:
f.close
os.moveFile(tmp, source)
main("data.txt", "data.txt.tmp")