Python Forum
Basic regex - Printable Version

+- Python Forum (
+-- Forum: Python Coding (
+--- Forum: General Coding Help (
+--- Thread: Basic regex (/thread-30840.html)

Basic regex - floatingshed - Nov-09-2020

I have never used the re module before.
I have many text files that need a phrase replacing, the following works fine:

for file in directory:

    open_file = open(file,'r')
    read_file =

    regex = re.compile('test phrase')
    read_file = regex.sub('new phrase', read_file)

    write_file = open(file, 'w')
But the phrase I need to replace is sometimes a path to a file and this fails.
How can I use the above if the test phrase is something like: 'D:\folder\another folder\file.exe'


RE: Basic regex - Gribouillis - Nov-09-2020

Double the backslashes and use a raw string
regex = re.compile(r'D:\\folder\\another folder\\file.exe')