1

How can I modify this function to increment the name when the filename "test.wav" already exists?

def write_float_to_16wav(signal, name = "test.wav", samplerate=20000):
    signal[signal > 1.0] = 1.0
    signal[signal < -1.0] = -1.0
    intsignal = np.int16((2**15-1)*signal)
    siow.write(name,samplerate,intsignal)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • do you want e.g. test1.wav as incremented name? – GordonW Jul 11 '19 at 17:57
  • @ScottishUser Yes, exactly. –  Jul 11 '19 at 17:58
  • First, you need to establish that it does, in fact, already exist. Just as it's not `siow.write`'s job to determine that, it's not really `write_float_to_16wav`'s job either; it's the job of whoever calls`write_float_to_16wav`. – chepner Jul 11 '19 at 18:03

3 Answers3

1

You can use os.path.exists to check for the existence of the file, and increment when needed:

import os.path

if os.path.exists(name):
    name_, ext = os.path.splitext(name)
    name = f'{name_}1{ext}'
    # For <3.6: '{name_}1{ext}'.format(name_=name_, ext=ext)

The above will check file in the current directory, if you want to check in some other directory, you can join the paths using os.path.join:

if os.path.exists(os.path.join(directory, name)):
heemayl
  • 39,294
  • 7
  • 70
  • 76
0

There are two main options. The first - and likely better - option is to simply count the number of wav files already created.

num_waves_created = 0
def write_float_to_16wav(signal, name = "test.wav", samplerate=20000):
    signal[signal > 1.0] = 1.0
    signal[signal < -1.0] = -1.0
    intsignal = np.int16((2**15-1)*signal)
    name = "test" + str(num_waves_created) + ".wav"
    siow.write(name,samplerate,intsignal)
    num_waves_created += 1

The second option is to test each time in the function if the file has already been created. This incorporates a while loop that operates at linear complexity, so it's efficient enough for 10 wav files, but can seriously slow down if you need to create more.

from os import path

def write_float_to_16wav(signal, name = "test.wav", samplerate=20000):
    new_path = False
    while (!new_path):
       if path.exists(name):
           break
       else:
           name_, ext = os.path.splitext(name)
           name = f'{name_}1{ext}'
    signal[signal > 1.0] = 1.0
    signal[signal < -1.0] = -1.0
    intsignal = np.int16((2**15-1)*signal)
    siow.write(name,samplerate,intsignal)
Matthew Anderson
  • 338
  • 1
  • 13
0

ok based on the limited code you have supplied and assuming you're not already validating if filename exists somewhere else:

1) Check if your filename already exists (see here)

2) If path/filename already exists extract the current path/filename name (see here), else filename = test.wav

3) From the current filename extract the last incremented value (using split or substring or whatever suits best)

4) Set the new filename with incremented value (see heemayl's answer)

5) Done.

GordonW
  • 1,120
  • 2
  • 16
  • 36