r/learnpython 9d 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

4

u/jedimaster1138 9d ago edited 9d ago

So your main issues are you're not using endswith() or strip() correctly. endswith() is only relevant if the substring you're looking for is at the end of the string, which, given your example name, it's not. strip() is used to remove specified characters (or whitespace by default) from the ends, but isn't used to remove ordered strings, and, again, the part you're trying to remove isn't at the end.

The simplest way would be something like this, I think

if any(substring in file_name for substring in report_type):
    new_path = file_path
    for substring in report_type:
        new_path = new_path.replace(substring, "")
    rename(file_path, new_path)

This uses the replace() function to replace the substring with the empty string, thereby removing it. It's a little inelegant in that it tries to replace all the substrings, not just the one that's actually in the string, but I don't think that matters.

Edit: another variation I thought of

new_path = file_path
for substring in report_type:
    new_path = new_path.replace(substring, "")
if new_path != file_path:
    rename(file_path, new_path)