My problem is that in order to do sub I need to escape a special character. But I don't want to modify the string that I'm substituting. Does Python have way to handle this?
fstring = r'C:\Temp\1_file.txt' #this is the new data that I want to substitute in
old_data = r'Some random text\n .*' #I'm looking for this in the file that I'll read
new_data = r'Some random text\n '+fstring #I want to change it to this
f = open(myfile,'r') #open the file
filedata = f.read() #read the file
newfiledata = re.sub(old_data,new_data,filedata) #substitute the new data
error: invalid group reference
\1 would normally imply a backreference to group 1 of the regex match, but that is not what you intend here (in fact no group 1, which is the reason for the error), you'll, therefore, need to escape the string so
re does not treat the
\1 as a metacharacter:
fstring = r'C:\Temp\\1_file.txt'