Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic regex
#1
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.
Reply
#2
Double the backslashes and use a raw string
regex = re.compile(r'D:\\folder\\another folder\\file.exe')
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020