I am trying to take a cpp file that has already been written and add header files to the list of includes using a python script. Currently, I create a string that has all of the includes that I want to add, and then using the re module I replace on of the includes with my string. All of the includes have a "\t" in there name, and this is causing issues; instead of printing the line as expected (#include "abc\type\GenericTypeMT.h
), I am getting #include "abc ype\GenericTypeMT.h
. When I print my string to the console, it has the expected form which leads me to believe that this is an re.sub issue and not an issue writing to the file. Below is an the code.
import re
import string
INCLUDE = "#include \"abc\\type\\"
with open("file.h", "r+") as f:
a = ""
b = ""
for line in file:
a = a + line
f.seek(0,0)
types = open("types.txt", "r+")
for t in types:
head = INCLUDE + t.strip() + "MT.h"
b = b + head + "\n"
a = re.sub(r'#include "abc\\type\\GenericTypeMT\.h"', b, a)
types.close()
print b
print a
f.write(a)
The output for b
is:
#include "abc\type\GenericTypeMT.h"
#include "abc\type\ServiceTypeMT.h"
#include "abc\type\AnotherTypeMT.h"
The (truncated) output for a
is:
/* INCLUDES *********************************/
#include "abc ype\GenericTypeMT.h"
#include "abc ype\ServiceTypeMT.h"
#include "abc ype\AnotherTypeMT.h"
#include <map>
...
The closest thing to my question that I could find was How to write \t to file using Python, but that is different than my problem, since mine seems to stem from the substitutions done by the regular expression, as shown by the print before the write.