Python: Find Substring In List Of String
I have two lists: songs is a list of song titles, filenames is a list of song MP3 files that is generated by running os.listdir(). songs = ['The Prediction', 'Life We Chose', 'Nast
Solution 1:
Here is a version that will maintain the file extension, whatever it was, and will avoid that the same filename is matched twice by deleting it from the filenames
array after a match. It also is case insensitive:
for song in songs:
for i, filename in enumerate(filenames):
if song.upper() in filename.upper():
os.rename(filename, song + os.path.splitext(filename)[1])
del filenames[i]
break
You could also loop first over the file names, but then the problem can also be that two file names match with the same song, and the rename
operation will raise an error on the second. So in that set up you'd better delete the song from the songs list once it has been matched with a file name.
Post a Comment for "Python: Find Substring In List Of String"