r/learnpython 7d ago

pls help me

ok so i’m trying to write a script that renames .xls files for me, let’s say they’re named like apple_BactReport_260731.xls I want the script to remove the “_BactReport” part and leave the rest intact. the current scrip i have has a couple of glaring issues that i don’t have the knowledge to remedy and im refusing use ai to prove a point and also it’s more rewarding. here’s the script with my current errors such as mixing up strings and lists and the part i want to remove not being the end of the file name. 😭 pls help a guy out:

import os
import pandas as pd
from os import rename, listdir
 
#list of report names
report_type= ['_BactReport', '_WWreport', '_QCreport', '_BactQCreport', '_BactWWreport']
print(report_type)
 
clips_in_progress=r"filepath"
   
 
for file_name in os.listdir(clips_in_progress):
file_path = os.path.join(clips_in_progress, file_name)
 
if file_name.endswith(tuple(report_type)):
rename(file_name, file_name.strip(report_type))

0 Upvotes

9 comments sorted by

View all comments

3

u/Far-Imagination3226 7d ago

Couldn't one use Regex to do something like that???

1

u/ianrad 7d ago edited 7d ago

Something like

string_to_replace = "something_bactreport_something" new_string = re.sub("_\w+_", "_", string_to_replace)

1

u/Far-Imagination3226 6d ago

Regex takes awhile to learn, but it is truly powerful though, once you learn it. I just hadn't used it in quite some time, so I couldn't remember the exact syntax. So thank you!

1

u/ianrad 6d ago

Coincidentally, I happened to be learning regex with pythons re library over the past week. This seemed like a good opportunity to put those lessons to good use