How can I use metadata to put audio files in directory?

Viewed 80

I downloaded a directory full of Audio file like

0001.wav
0002.wav
...
4555.wav

and I also downloaded the dataset.csv related to these files which contains metadata like the name of the sound ( the number before the .wav) and the label (exemple: first column is nameand seconde column is label, in the first row I have 0001 and Electric_guitar .

With pandas,I sorted all my data by label so I created many tables like Electric_guitar.csv or scream.csv and now I want to classify in differents directories all my audio files using these tables. I search on internet but I didnt find anything that help me, maybe I have trouble to formulate my issues.

How am I supposed to do that? ty

1 Answers

Use Pandas read_csv with dtype=str to make sure the name column will not be interpreted as a number (e.g. where 0009 could become 9). Use itertuples to iterate over rows as namedtuples, don't use iterrows in this case since:

...iterrows returns a Series for each row, it does not preserve dtypes across the rows (dtypes are preserved across columns for DataFrames)

Then, for each row, use os.makedirs to create the folder (if doesn't already exist) using the label name as parameter, and finally, move the files to the appropriate label folder with os.rename.

Input sounds.metafile

name,label
00000,talking
00001,talking
00002,drums
00003,eletric_guitar
00004,scream
00005,scream
00006,scream
00007,eletric_guitar
00008,talking
00009,eletric_guitar
import pandas as pd
import os

df = pd.read_csv('sounds.metafile', dtype=str)
print(df)

for row in df.itertuples():
    # create a folder for each label
    os.makedirs(f"output/{row.label}", exist_ok=True)
    #  move files
    os.rename(f'audio_files/{row.name}.wav', f'output/{row.label}/{row.name}.wav')

Output folder structure

output
├── drums
│   └── 00002.wav
├── eletric_guitar
│   ├── 00003.wav
│   ├── 00007.wav
│   └── 00009.wav
├── scream
│   ├── 00004.wav
│   ├── 00005.wav
│   └── 00006.wav
└── talking
    ├── 00000.wav
    ├── 00001.wav
    └── 00008.wav
Related