-2

I have a list of WAV files in a folder of data showing in the format of hours, minutes and second.

For example,

C:\Users\Desktop\Data

01h02m02s.wav
01h02m13s.wav
01h02m24s.wav

I need the filename to be modified, programmatically such that it needs to be converted into seconds. How do I do it?

3722s.wav
3733s.wav
3744s.wav

Would appreciate all feedback and help.

Thank you

user2995019
  • 53
  • 1
  • 1
  • 9
  • see https://stackoverflow.com/questions/7833807/get-wav-file-length-or-duration and os.rename(old,new) – Israel-abebe Oct 09 '17 at 11:19
  • Get the parts for hours, minutes and seconds from the string. Multiply hours with 3600, multiply minutes with 60, take the seconds and add it up. So if `data = '01h02m02s.wav'` you would have `sum([int(data[:2]) * 3600, int(data[3:5]) * 60], int(data[6:8]))` and that gives you`3722`. – Matthias Oct 09 '17 at 11:21

2 Answers2

2

Use glob.glob() to get your file list and then an regular expression to try and extract the hours, minutes and seconds from the filename. os.rename() is used to actually rename the file:

import glob
import re
import os

path = r'C:\Users\Desktop\Data'

for wav in glob.glob(os.path.join(path, '*.wav')):
    re_hms = re.findall(r'(\d+)h(\d+)m(\d+)s\.wav', wav)

    if re_hms:
        hours, minutes, seconds = map(int, re_hms[0])
        total_seconds = hours * 3600 + minutes * 60 + seconds
        new_wav = os.path.join(path, '{}s.wav'.format(total_seconds))
        print "{} -> {}".format(wav, new_wav)
        os.rename(wav, new_wav)

os.path.join() is used to safely join file paths together without having to worry about adding path separators.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
0

You could use this if all the files in the path are WAV and their names have the pattern as shown by you.

import os

path = r'C:\Users\Desktop\Data'
waves = os.listdir(path)

for wave in waves:
    hours, minutes, seconds = map(int, [wave[:2], wave[3:5], wave[6:8]])
    total_seconds = hours * 3600 + minutes * 60 + seconds
    new_name = os.path.join(path, "{}s.wav".format(total_seconds))

    os.rename(os.path.join(path, wave), new_name)
srikavineehari
  • 2,502
  • 1
  • 11
  • 21