【发布时间】:2013-01-15 11:26:59
【问题描述】:
我正在尝试使用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='')
我就是这样使用它的:
ReplaceInFile(r'Path\To\File.iss', r'(#define RootDir\s+)(.+)', r'\g<1>' + os.getcwd())
不幸的是,我的路径是 C:\Tkbt\Launch,所以我得到的替换是:
#define RootDir C: kbt\Launch
即它将\t 解释为选项卡。
所以在我看来,我需要告诉 python 双重转义来自 os.getcwd() 的所有内容。我想也许.decode('unicode_escape') 可能是答案,但事实并非如此。谁能帮帮我?
我希望有一个解决方案不是“用'\\' 替换每个'\'”。
【问题讨论】:
-
它不仅仅是 os.getcwd() - 它是任何路径。 re.escape() 也不起作用,因为它转义了 ':' - C\:\Tkbt\Launch
-
你不能用
/代替\吗? -
@fp:
os.getcwd()返回带有反斜杠的路径。这与路径文字无关。
标签: python regex python-3.x