我是python的新手。我拼凑了一个非常有用的代码,除了当我在find_str变量的字符串中有方括号时。我尝试使用双括号,但这也不起作用。
目标是将包含_(FAIL)_
的CSV列表中的所有文本替换为SUCCESS
。
这是我的代码:
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)
答案 0 :(得分:2)
无需使用正则表达式和re.sub()
,str.replace()
可以完成工作:
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)
礼物:
We go through life and SUCCESS and SUCCESS and SUCCESS
答案 1 :(得分:0)
看起来您需要逃脱括号
尝试:
find_str = "_\(FAIL\)_"
replace_str = "SUCCESS"
# substitute
new_csv_str = re.sub(find_str, replace_str, my_csv_text)