影刀RPA 文件内容批量查找替换 影刀RPA 文件内容批量查找替换作者林焱什么情况用什么需要在一批文件中批量替换某个关键词——公司名改了要更新所有文档、价格表调整了要批量修改、敏感词需要批量替换为脱敏文本。在影刀RPA里可以针对文本文件、CSV、Excel分别实现批量查找替换。适用场景批量更新文档内容、批量修改配置文件、敏感词替换、公司名/品牌名统一更新。怎么做店群矩阵自动化突破运营极限文本文件批量替换importosdefbatch_replace_text(folder,old_text,new_text,extensionsNone):批量替换文本文件内容ifextensionsisNone:extensions[.txt,.csv,.json,.xml,.html,.md,.py]results[]forfilenameinos.listdir(folder):filepathos.path.join(folder,filename)ifnotos.path.isfile(filepath):continueextos.path.splitext(filename)[1].lower()ifextnotinextensions:continuetry:# 读取文件内容# 尝试不同编码contentNoneforencodingin[utf-8,gbk,gb2312,utf-8-sig]:try:withopen(filepath,r,encodingencoding)asf:contentf.read()breakexceptUnicodeDecodeError:continueifcontentisNone:results.append({file:filename,status:编码无法识别})continue# 统计替换次数countcontent.count(old_text)ifcount0:# 替换new_contentcontent.replace(old_text,new_text)# 写回文件withopen(filepath,w,encodingencoding)asf:f.write(new_content)results.append({file:filename,status:成功,替换次数:count})else:results.append({file:filename,status:未找到,替换次数:0})exceptExceptionase:results.append({file:filename,status:f错误:{e}})returnresults# 使用把所有文件中的旧公司名替换为新公司名resultsbatch_replace_text(folderrC:\Documents,old_text旧公司名,new_text新公司名)forrinresults:print(f{r[file]}:{r[status]}({r.get(替换次数,0)}处))Excel批量替换importpandasaspdimportopenpyxldefbatch_replace_excel(filepath,replacements,sheet_nameNone): Excel批量替换 replacements: {旧文本: 新文本, ...} wbopenpyxl.load_workbook(filepath)sheets[wb[sheet_name]]ifsheet_nameelsewb.worksheets total_count0forwsinsheets:forrowinws.iter_rows():forcellinrow:ifcell.valueandisinstance(cell.value,str):originalcell.value new_valueoriginalforold_text,new_textinreplacements.items():ifold_textinnew_value:![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/5dd553f93aa24c148ec02377e50dc0bf.png#pic_center)![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/9373b734725d49c480b6f21dcdff7058.png#pic_center)new_valuenew_value.replace(old_text,new_text)ifnew_value!original:cell.valuenew_value total_count1wb.save(filepath)returntotal_count# 使用countbatch_replace_excel(filepathrC:\Data\report.xlsx,replacements{2025年:2026年,旧部门名:新部门名,旧产品名:新产品名,})print(f共替换{count}处)正则表达式替换importredefregex_replace_in_file(filepath,pattern,replacement,encodingutf-8):用正则表达式替换文件内容withopen(filepath,r,encodingencoding)asf:contentf.read()# 替换new_content,countre.subn(pattern,replacement,content)ifcount0:withopen(filepath,w,encodingencoding)asf:f.write(new_content)returncount# 使用替换所有手机号为脱敏格式countregex_replace_in_file(filepathrC:\Data\contacts.txt,patternr1[3-9]\d{9},replacement[手机号已脱敏])# 替换所有日期格式 2026/07/01 → 2026-07-01countregex_replace_in_file(filepathrC:\Data\dates.txt,patternr(\d{4})/(\d{2})/(\d{2}),replacementr\1-\2-\3)多文件批量替换defbatch_replace_all(folder,replacements,extensionsNone): 在整个文件夹中批量替换多个关键词 replacements: {旧文本: 新文本, ...} ifextensionsisNone:extensions[.txt,.csv,.json,.html,.md]all_results[]forfilenameinos.listdir(folder):filepathos.path.join(folder,filename)ifnotos.path.isfile(filepath):continueextos.path.splitext(filename)[1].lower()ifext.xlsx:# Excel文件单独处理try:countbatch_replace_excel(filepath,replacements)all_results.append({file:filename,类型:Excel,替换数:count})exceptExceptionase:all_results.append({file:filename,类型:Excel,错误:str(e)})elifextinextensions:# 文本文件try:contentread_file_auto(filepath)total0forold,newinreplacements.items():totalcontent.count(old)contentcontent.replace(old,new)iftotal0:write_file_auto(filepath,content)all_results.append({file:filename,类型:文本,替换数:total})exceptExceptionase:all_results.append({file:filename,类型:文本,错误:str(e)})# 生成报告importpandasaspd pd.DataFrame(all_results).to_excel(os.path.join(folder,替换报告.xlsx),indexFalse)total_replacementssum(r.get(替换数,0)forrinall_results)print(f共处理{len(all_results)}个文件替换{total_replacements}处)returnall_resultsdefread_file_auto(filepath):自动检测编码读取文件forencodingin[utf-8,gbk,utf-8-sig]:try:withopen(filepath,r,encodingencoding)asf:returnf.read()exceptUnicodeDecodeError:continuereturndefwrite_file_auto(filepath,content):写入文件withopen(filepath,w,encodingutf-8)asf:f.write(content)影刀RPA查找替换流程【设置变量】 target_folder rC:\Documents replacements {旧词: 新词, 2025: 2026} 【执行Python代码】 results batch_replace_all( folderyd_var[target_folder], replacementsyd_var[replacements] ) 【输出信息】 共处理X个文件替换Y处 详见替换报告.xlsx有什么坑temu店群自动化报活动案例坑1替换破坏了文件结构# 问题在JSON文件中替换了不该替换的内容# 如把 {name: test} 中的test替换了但JSON结构被破坏# 解决对结构化文件JSON/XML用专门的解析器importjsondefsafe_replace_json(filepath,key,old_value,new_value):安全替换JSON中的值withopen(filepath,r,encodingutf-8)asf:datajson.load(f)# 递归替换defreplace_in_dict(d):fork,vind.items():ifvold_value:d[k]new_valueelifisinstance(v,dict):replace_in_dict(v)elifisinstance(v,list):fori,iteminenumerate(v):ifitemold_value:v[i]new_valueelifisinstance(item,dict):replace_in_dict(item)replace_in_dict(data)withopen(filepath,w,encodingutf-8)asf:json.dump(data,f,ensure_asciiFalse,indent2)坑2编码导致乱码# 问题GBK编码的文件用UTF-8读取后替换写回中文全乱码# 解决先检测编码再操作importchardetdefdetect_encoding(filepath):检测文件编码withopen(filepath,rb)asf:rawf.read(10000)resultchardet.detect(raw)returnresult[encoding]encodingdetect_encoding(filepath)withopen(filepath,r,encodingencoding)asf:contentf.read()# 替换后用相同编码写回withopen(filepath,w,encodingencoding)asf:f.write(new_content)坑3替换了不该替换的# 问题替换张三时张三丰也变成了李四丰content.replace(张三,李四)# 张三丰 → 李四丰# 解决用正则加边界importre re.sub(r\b张三\b,李四,content)# 只替换完整的张三![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/a18e10fcaa5a46ccbdbc39cf761146e0.png#pic_center)# 中文边界需要自己定义re.sub(r(?![一-龥])张三(?![一-龥]),李四,content)坑4文件被占用无法写入# 问题Excel文件正被打开写入报PermissionError# 解决先检查文件是否被占用importosdefis_file_locked(filepath):检查文件是否被占用ifnotos.path.exists(filepath):returnFalsetry:# 尝试重命名如果文件被占用会失败os.rename(filepath,filepath)returnFalseexceptOSError:returnTrueifis_file_locked(filepath):print(f文件被占用:{filepath})# 跳过或等待坑5BOM头导致替换失败# 问题UTF-8 with BOM的文件第一个字符前有\ufeff# 替换时第一个词匹配不上# 解决读取时用utf-8-sig编码自动去除BOMwithopen(filepath,r,encodingutf-8-sig)asf:contentf.read()# BOM自动去除![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/af2e27e99db44720bf62a0b778bf54b1.png#pic_center)![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/c1f6a22f74e34eccabb4a62bfa0a5cf1.png#pic_center)# 写回时不需要BOMwithopen(filepath,w,encodingutf-8)asf:f.write(content)# 无BOM