I have to edit some text files to include new information, but I will need to insert that information at specific locations in the file based on the surrounding text.
Th
This will look for any string, in the file (not specific, to be at the start of the line only, i.e. can exist spread over multiple lines as well).
Typically you can follow the algo as:
Let us see code:
#!/usr/bin/python
import os
SEARCH_WORD = 'search_text_here'
file_name = 'sample.txt'
add_text = 'my_new_text_here'
final_loc=-1
with open(file_name, 'rb') as file:
fsize = os.path.getsize(file_name)
bsize = fsize
word_len = len(SEARCH_WORD)
while True:
found = 0
pr = file.read(bsize)
pf = pr.find(SEARCH_WORD)
if pf > -1:
found = 1
pos_dec = file.tell() - (bsize - pf)
file.seek(pos_dec + word_len)
bsize = fsize - file.tell()
if file.tell() < fsize:
seek = file.tell() - word_len + 1
file.seek(seek)
if 1==found:
final_loc = seek
print "loc: "+str(final_loc)
else:
break
# create file with doxygen comments
f_old = open(file_name,'r+')
f_new = open("new.txt", "w")
f_old.seek(0)
fStr = str(f_old.read())
f_new.write(fStr[:final_loc-1]);
f_new.write(add_text);
f_new.write(fStr[final_loc-1:])
f_new.close()
f_old.close()