Python 3:我怎么能得到操作系统getcwd()玩得很好re.sub公司()?

2024-09-29 19:26:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用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 '\''\\'”。在


Tags: 文件inre目录内容deflineopen
1条回答
网友
1楼 · 发布于 2024-09-29 19:26:02

你不得不求助于.replace('\\', '\\\\')恐怕这是你唯一能让这个工作成功的选择。在

  • 使用编码来unicode_escape,然后从ASCII再次解码,如果可以的话:

    replacepattern = r'\g<1>' + os.getcwd().encode('unicode_escape').decode('ascii')
    

    这对路径是正确的:

    ^{pr2}$

    但不能使用现有的非ASCII字符,因为re.sub()不处理\u或{}转义。

  • 不要使用^{}来转义字符串中的特殊字符,这会导致转义太多:

    >>> print(re.sub(r'(#define RootDir\s+)(.+)', r'\g<1>' + re.escape(r'C:\Path\To\File.iss'), '#define RootDir foo/bar/baz'))
    #define RootDir C\:\Path\To\File\.iss
    

    注意这里的\:

只有.replace()会产生工作替换模式,包括非ASCII字符:

>>> print(re.sub(r'(#define RootDir\s+)(.+)', r'\g<1>' + 'C:\\Path\\To\\File-with-non-
ASCII-\xef.iss'.replace('\\', '\\\\'), '#define Root
#define RootDir C:\Path\To\File-with-non-ASCII-ï.iss

相关问题 更多 >

    热门问题