Python script to batch-rename .WAV files in a directory, based on audio length

I'm writing a Python Script that renames a bunch of .WAV files in a directory, and renames them, add the length of the audio file to the beginning of the file name.

What I got so far now is:

import wave
import contextlib
import os


for file_name in os.listdir(os.getcwd()):
    if file_name.endswith(".wav") or file_name.endswith(".aiff"):
        with contextlib.closing(wave.open(file_name, 'r')) as f:
            frames = f.getnframes()
            rate = f.getframerate()
            duration = frames / float(rate)
            duration = int(duration)
            duration = str(duration)
            new_file_name = duration + " " + file_name
            print(file_name)
            os.rename(file_name, new_file_name)
    else:
        continue

But I got this error:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'TEMFX01-RisingLong001.wav' -> '15 TEMFX01-RisingLong001.wav'

How can I make the process stop using it so I can rename it?

Thanks!

EDIT: Really silly, just needed to add f.close() before print(file_name).

Not sure if I should delete this topic or answer my own question?

Upvotes: 0

Views: 1606

Answers (2)

import wave
import contextlib
import os
count = 0

for file_name in os.listdir(os.getcwd()):
    if file_name.endswith(".wav") or file_name.endswith(".aiff"):
        count += 1
        with contextlib.closing(wave.open(file_name, 'r')) as f:
            frames = f.getnframes()
            rate = f.getframerate()
            duration = frames / float(rate)
            duration = int(duration)
            duration = str(duration)
            new_file_name = "audio" + str(count) + '.wav'
            print(file_name)
        os.rename(file_name, new_file_name)
    else:
        continue

This code will resolve the issue

Upvotes: 0

mntl_
mntl_

Reputation: 356

Close the wave before renaming.

import wave
import contextlib
import os


for file_name in os.listdir(os.getcwd()):
    if file_name.endswith(".wav") or file_name.endswith(".aiff"):
        with contextlib.closing(wave.open(file_name, 'r')) as f:
            frames = f.getnframes()
            rate = f.getframerate()
            duration = frames / float(rate)
            duration = int(duration)
            duration = str(duration)
            new_file_name = duration + " " + file_name
            print(file_name)
            wave.close()
            os.rename(file_name, new_file_name)
    else:

Upvotes: 2

Related Questions