我在一个文件中有以下文本:
C:\Program Files\MyApp\
我想解析我的文件并将文本替换为:
D:\NewDest\
我使用下面的代码,但是我不能替换文本因为反斜杠-任何没有反斜杠的文本都可以。我该怎么办?在
import os, fnmatch
import fileinput, glob, string, sys, os
from os.path import join
import os
import re
import sys
def searchreplace(path,search,replace,exts=None):
import fileinput, glob, string, sys, os
from os.path import join
# replace a string in multiple files
#filesearch.py
files = glob.glob(path + "/*")
if files is not []:
for file in files:
if os.path.isfile(file):
if exts is None or exts.count(os.path.splitext(file)[1]) is not 0:
print file
for line in fileinput.input(file):
line = re.sub(search,replace, line.rstrip())
print(line)
searchreplace('D:\Test', 'C:\Program Files\MyApp\', 'D:\NewDest\', '*.csproj')
一个反斜杠考虑转义序列。在
您可以使用双斜杠。Windows允许使用双斜杠(“C:\Program Files\MyApp\”,“D:\NewDest\”)。在
您需要将路径中的
\
替换为\\
。以及正则表达式中每个
\
的\\\\
。在参考号:Can't escape the backslash with regex?
尝试使用'D:\\Test'或r'D:\Test'代替'D:\Test'将反斜杠设为文字。所有字符串都一样。在
相关问题 更多 >
编程相关推荐