I have a Django site where users upload and have the option to delete files. There will be a lot of files that will have the same logical name so I append numbers to them:
foo/bar/file.mp3 foo/bar/file2.mp3...
I needed a method that would return the lowest file number not currently being used. I have a working example here, but it feels wrong and ugly and I don't know if there is an easier way of doing it. If I ran the method on the examples above, it would return "1" so I know I can make the next file foo/bar/file1.mp3
.
def get_num(self, files):
"""function to extract the lowest file number to save as, returns string. Takes a list as input"""
nums = []
for f in files:
# Call the unicode function which should return the string path
match = re.findall("([\d]+)\.[\w]+", f.__unicode__())
if match:
nums.append(int(match[0]))
else:
nums.append(0)
for i in range(len(nums) + 1):
if i not in nums:
if i == 0:
return ""
else:
return str(i)