Hawkmoon
Hawkmoon

Reputation: 5

Rename multiple files in Python from another list

I am trying to rename multiple files from another list. Like rename the test.wav to test_1.wav from the list ['_1','_2'].

import os
list_2 = ['_1','_2']
path = '/Users/file_process/new_test/'
file_name = os.listdir(path)

for name in file_name:
   for ele in list_2:
      new_name = name.replace('.wav',ele+'.wav')
      os.renames(os.path.join(path,name),os.path.join(path,new_name))

But turns out the error shows "FileNotFoundError: [Errno 2] No such file or directory: /Users/file_process/new_test/test.wav -> /Users/file_process/new_test/test_2.wav

However, the first file in the folder has changed to test_1.wav but not the rest.

Upvotes: 0

Views: 65

Answers (2)

ssd
ssd

Reputation: 2432

You've got error in your algorithm.

Your algorithm first gets through the outer loop (for name in file_name) and then in the inner loop, you replace the file test.wav to test_1.wav. At this step, there is no file named test.wav (it has been already replaced as test_1.wav); however, your algorithm, still, tries to rename the file named test.wav to test_2.wav; and can not find it, of course!

Upvotes: 0

Naveen
Naveen

Reputation: 1210

You are looping against 1st file with a total list. You have to input both the list and filename in the single for loop.

This can be done using zip(file_name, list_2) function.

This will rename the file with appending whatever is sent through the list. We just have to make sure the list and the number of files are always equal.

Code:

import os
list_2 = ['_1','_2']
path = '/Users/file_process/new_test/'
file_name = os.listdir(path)

for name, ele in zip(file_name, list_2):
    new_name = name.replace(name , name[:-4] + ele+'.wav')
    print(new_name)
    os.renames(os.path.join(path,name),os.path.join(path,new_name))

Upvotes: 1

Related Questions