Ive made this quick program to strip the "youtube - " prefix off my mp3 collection, so i started modifying a script i had made before to replace file names with a <filename><incrementing number> type name.

It has gone well so far, with the only problem being it will strip "you" as oposed to the entire thing if the song title begins with you as you will see in my output.

Can anyone help?

import os, string
from os.path import join as pjoin, isdir
while True:
    targetfolder = raw_input('enter a target folder:\n').strip()
    if isdir(targetfolder):
        print("you must enter an existing folder!")
toBeStripped = "YouTube        -" #raw_input('enter a string to be stripped:\n')
for fname in os.listdir(targetfolder):
    print fname
    c = os.path.splitext(fname) # so the file extension remains the same after edit
    fname2 = c[0].strip(toBeStripped) + c[1]  # tries stripping the phrase
    newname = pjoin(targetfolder, fname2)
    print fname2
    os.rename(fname, newname)

Thank you for your time.

6 Years
Discussion Span
Last Post by Archenemie

String.strip removes any combination of the given chars. See python documentation for that.

You can use regexp or string.startswith.
If the filename starts with the string to be stripped, then change the filename by removing the first charachters that are string to be stripped long.

Edited by slate: n/a


Try to replace line 18 with following line, remember to add 'import re'.

fname2 = re.sub(r'%s(.*)' % toBeStripped, r'\1', c[0]) + c[1]
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.