set names from text list to wav files in python

In order to set names from a text list to wav files in Python, you can use the os module and regular expressions (regex). By following the steps outlined below, you can rename your audio files based on the names in the text file.

  1. Import the necessary modules
main.py
import os
import re
20 chars
3 lines
  1. Read the names from the text file
main.py
with open('list.txt', 'r') as f:
    names = f.read().splitlines()
67 chars
3 lines
  1. Use os module to access the directory with the wav files and loop over the files
main.py
for filename in os.listdir('/path/to/audio/files'):
    if filename.endswith('.wav'):
        # Add code here
110 chars
4 lines
  1. Use regular expressions to extract the index of the wav file's name
main.py
index = re.search("\\d+", filename).group(0)
45 chars
2 lines
  1. Use os.rename() to set the new name of the wav file
main.py
os.rename(filename, names[int(index)-1] + '.wav')
50 chars
2 lines

Putting it all together, here's the full code:

main.py
import os
import re

with open('list.txt', 'r') as f:
    names = f.read().splitlines()

for filename in os.listdir('/path/to/audio/files'):
    if filename.endswith('.wav'):
        index = re.search("\\d+", filename).group(0)
        os.rename(filename, names[int(index)-1] + '.wav')
286 chars
11 lines

Make sure to replace /path/to/audio/files with the actual path to your directory containing the wav files, and list.txt with the name of the text file containing the new names.

gistlibby LogSnag