Só precisas de fazer o seguinte:
import os
filename = 'video0.avi'
if os.path.exists(filename):
tmp = filename.split('.avi')
count = tmp[0].replace('video', '') or 0
count = int(count) + 1
new_filename = 'video{0}.avi'.format(count)
Basicamente, verificas se existe em disco, vais precisar do path para a localização do ficheiro, depois fazes um split pelo ponto e a entensão do ficheiro depois removes o nome base e incrementas o resultado, se não existir com o "or 0" adiciona um defalt.
O mesmo com função.
import os
def load_file(filename):
if os.path.exists(filename):
tmp = filename.split('.avi')
count = tmp[0].replace('video', '') or 0
count = int(count) + 1
return 'video{0}.avi'.format(count)
return filename
filename = 'video.avi'
print(load_file(filename))
Percorrendo toda a diretoria.
import os, re, os.path
def load_file(file):
number = []
onlyfiles = [f for f in os.listdir('.') if os.path.isfile(os.path.join('.', f))] # load all dir files
filename, file_extension = os.path.splitext(file) # load filename and extension from parameter file
total_files = len(onlyfiles) # get total files in dir
splitter = re.compile(r'\d+') # build a splitter to get digits part of file name
number = splitter.findall(filename) or ['0'] # get number part from filename
only_name = filename.replace(number[0], '') # get only name from filename removing the number from it
i = 0
matching = [s for s in onlyfiles if only_name in s] # build array only with files names that match the only_name (from file name)
if len(matching) == 0: # if no files matchs the criteria returns the name itself, don't exist any
return file
while i < len(matching): # interates only the array of matching files and extracts the number from it
number.append((splitter.findall(matching[i]) or [0])[0]) # add to number array the numbers from file found
i += 1
number = [int(i) for i in number] # converts all number array to int (cast), some of then are strings
largest_number = max(number) # get the max value from array
return '{0}{1}{2}'.format(only_name, str(largest_number + 1), file_extension) # returns the new file number
filename = 'video.avi'
print(load_file(filename))
out = cv2.VideoWriter(load_file(filename), fourcc, fps, (int(width), int(height)))