我试图使用python 3.3
将文件中的某些内容替换为当前工作目录。我有:
def ReplaceInFile(filename, replaceRegEx, replaceWithRegEx):
''' Open a file and use a re.sub to replace content within it in place '''
with fileinput.input(filename, inplace=True) as f:
for line in f:
line = re.sub(replaceRegEx, replaceWithRegEx, line)
#sys.stdout.write (line)
print(line, end='')
我是这样用的:
^{pr2}$不幸的是,我的路径是C:\Tkbt\Launch,所以我得到的替换是:
#define RootDir C: kbt\Launch
例如,它将\t
解释为制表符。在
所以在我看来,我需要告诉python对os.getcwd()
的所有内容进行双重转义。我以为.decode('unicode_escape')
可能是答案,但事实并非如此。有人能帮我吗?在
我希望有一个解决方案不是“find replace each '\'
为'\\'
”。在
你不得不求助于
.replace('\\', '\\\\')
恐怕这是你唯一能让这个工作成功的选择。在使用编码来
unicode_escape
,然后从ASCII再次解码,如果可以的话:这对路径是正确的:
^{pr2}$但不能使用现有的非ASCII字符,因为}转义。
re.sub()
不处理\u
或{不要使用^{} 来转义字符串中的特殊字符,这会导致转义太多:
注意这里的
\:
。只有
.replace()
会产生工作替换模式,包括非ASCII字符:相关问题 更多 >
编程相关推荐