0

I'm trying to teach myself Python and I have a simple program that records some audio and sends it to an output file. I can't seem to figure out exactly how to increment the file each time I run it to avoid overwriting the previous one (output1.wav, output2.wav, etc). It seems simple, but as I said I am very new to Python and can't seem to get it to work.

import os
import sounddevice as sd
from scipy.io.wavfile import write


os.chdir(r'C:\Path') 
fs = 44100 
seconds = 20 
myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=2)
sd.wait() 

write('output.wav', fs, myrecording)  
Townes
  • 1
  • 1
  • you need to test if the file exists before writing it – RMPR Feb 24 '20 at 20:55
  • 2
    Does this answer your question? [How do I create a incrementing filename in Python?](https://stackoverflow.com/questions/17984809/how-do-i-create-a-incrementing-filename-in-python) – rdas Feb 24 '20 at 20:56
  • If you just need to save the output into a new file each time, why not use [tempfile.mkstemp](https://docs.python.org/3/library/tempfile.html)? See [this QA](https://stackoverflow.com/questions/38436987/python-write-in-mkstemp-file) – Pynchia Feb 24 '20 at 21:06

2 Answers2

0

You first have to find out what the last file you wrote to was, then increment that by one and generate the new filename:

import glob 
import re

files=glob.glob("Output*.wav")
print(files)
numbers = [int(re.search("Output(\d+).wav", s).group(1)) for s in files]
next_num = max(numbers)+1
print(numbers)
new_filename = f"Output{next_num}.wav"
print(new_filename)

I used a regular expression search from the re library to extract the filenumber.

divingTobi
  • 2,044
  • 10
  • 25
0

Incrementing and writing to the next available number multiple times ends up being an O(n^2) operation, which can get very slow for large collections.

What if you use a UUID instead? It's simple, it's O(n) and it's extremely unlikely to cause a collision: https://docs.python.org/3/library/uuid.html#example

dstromberg
  • 6,954
  • 1
  • 26
  • 27