1

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)
Martin
  • 594
  • 1
  • 8
  • 32

2 Answers2

2

No need to use a regular expression and re.sub() for this, str.replace() will do the job:

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

my_csv_text = 'We go through life and _(FAIL)_ and _(FAIL)_ and _(FAIL)_'

new_csv_str = my_csv_text.replace(find_str, replace_str)

print(new_csv_str)

Gives:

We go through life and SUCCESS and SUCCESS and SUCCESS
cdarke
  • 42,728
  • 8
  • 80
  • 84
0

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)
Rakesh
  • 81,458
  • 17
  • 76
  • 113