0

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.

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Very appreciated!
0

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!

1 Comment

Thank you! Very appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.