Python Forum

Full Version: Basic regex
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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 = open_file.read()

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

    write_file = open(file, 'w')
    write_file.write(read_file)
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'

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