search and replace a windows path in a file using python

Question:

I have the following text in a file:

C:Program FilesMyApp

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 FilesMyApp', 'D:NewDest', '*.csproj')
Asked By: pogorman

||

Answers:

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 FilesMyApp”, “D:NewDest”).

Answered By: user3273866

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

Answered By: haraprasadj

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?

Answered By: Chien-Wei Huang