![]() |
Basic regex - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- 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 = 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. 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') |