Search code examples
pythonregexpython-3.xbrackets

Need Help using string with brackets


I am a total newb to python. I pieced together a code that works great except when I have brackets in the string for the find_str variable. I tried using double brackets but it doesn't work either.

The goal is to replace all text in a list of CSV's that contain _(FAIL)_ with SUCCESS.

Here is my code:

import glob
import re


filenames = sorted(glob.glob('*.csv'))
filenames = filenames
for f2 in filenames:

    csv_name=f2

    # open your csv and read as a text string
    with open(csv_name, 'r') as f:
        my_csv_text = f.read()

    find_str = "_(FAIL)_"
    replace_str = "SUCCESS"


    # substitute
    new_csv_str = re.sub(find_str, replace_str, my_csv_text)


    # open new file and save
    new_csv_path = csv_name 
    with open(new_csv_path, 'w') as f:
        f.write(new_csv_str)

Solution

  • Look like you need to escape the brackets

    Try:

    find_str = "_\(FAIL\)_"
    replace_str = "SUCCESS"
    
    # substitute
    new_csv_str = re.sub(find_str, replace_str, my_csv_text)