Skip to content
Advertisement

How to rename files on MacOS Big Sur 11.4 using Python 3.9.5, not batch or sequential, using a list/CSV file(s)?

I have found many questions that have helped me get to where I am at now, but am stuck moving forward.

End goal: I have ~1500 audio files with meaningless names (each 9 characters long and a mix of numbers and letters; i.e. 4a96det8g). I have a table with the meaningless name in one column and a useful name in a second column (for example: Getting There). I want to rename all files to the useful name that coincides with the meaningless names, and then keep whatever extension is on each file (there is a mix of .m4a and .mp4).

Where I am at in Python: I have split the table in 2 different CSV files, and loaded them into IDLE as lists: ID_List (meaningless names) and Names_List (useful list). I have not sort the lists in Python, so each index is applicable to the same index in the other list.

Here is the code I have so far:

for i in ID_List:
    for file in os.listdir("/Volumes/2TB Portabl/Audios copy 2"):
        if(file.startswith(ID_List[i])):
            oldtext = os.path.splitext(file)[1]
            os.rename(file, Names_List[i] + oldtext)

The error I am getting is:

Traceback (most recent call last):
  File "<pyshell#30>", line 3, in <module>
    if(file.startswith(ID_List[i])):
TypeError: list indices must be integers or slices, not str

So somewhere I am needing to force the return from ID_List to be a string??? Or maybe there is an easier way to do this all together?

Advertisement

Answer

You iterate through the values in the list, not the index. That’s why TypeError: list indices must be integers or slices, not str occurs. Try to iterate by the index.

for i in range(len(ID_List)):
    for file in os.listdir("/Volumes/2TB Portabl/Audios copy 2"):
        if(file.startswith(ID_List[i])):
            oldtext = os.path.splitext(file)[1]
            os.rename(file, Names_List[i] + oldtext)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement