我对Python完全陌生,这是我第一个替换word的脚本。
我的文件test.c
包含以下两行
printf("\nReboot not supported. Exiting instead.\n");
fprintf(stderr, "FATAL: operation not supported!\n");
现在,我想分别用printf
和fprintf
替换//printf
和//fprintf
。
这是我尝试过的
infile = open('path\to\input\test.c')
outfile = open('path\to\output\test.c', 'w')
replacements = {'printf':'//printf', 'fprintf':'//fprintf'}
for line in infile:
for src, target in replacements.iteritems():
line = line.replace(src, target)
outfile.write(line)
infile.close()
outfile.close()
但是使用这个我得到了
fprintf
到//f//printf
这是错误的。
对于解决方案,已查看此answer,但无法将其放入我的脚本中。
有人知道我该如何解决吗?
python大神给出的解决方案
基本上,您想将printf转换为// printf,将fprintf转换为// fprintf。如果是这种情况,则可能会起作用,请尝试一下。
outfile = open("test.c", 'r')
temp = outfile.read()
temp = re.sub("printf", "//printf", temp)
temp = re.sub("f//printf", "//fprintf", temp)
outfile.close()
outfile = open("test.c","w")
outfile.write(temp)
outfile.close()