Question

I have the following text in a file:

C:\Program Files\MyApp\

I want to parse my file and replace the text with :

D:\NewDest\

I use the following code, but i cant replace the text because of the backslash - any text without a backslash works fine. What do I do?

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')
Was it helpful?

Solution

You need to replace \ with \\ in your path.
And also \\\\ for each \ in your regex.

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\\\\', '*.txt')

Ref: Can't escape the backslash with regex?

OTHER TIPS

One back slash consider escape sequnce.

>>> a ="\"
  File "<stdin>", line 1
    a ="\"
         ^
SyntaxError: EOL while scanning string literal
>>> a ="\\"

You can use double slash .Windows allow double slash("C:\Program Files\MyApp\", "D:\NewDest\").

Try using 'D:\\Test' or r'D:\Test' instead of 'D:\Test' to make the backslash a literal. Same for all strings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top