Search code examples
pythonregexreplacepathbackslash

search and replace a windows path in a file using python


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')

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?