Python Forum

Full Version: How to Make Unique .txt titles
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello! I'm trying to find a way to make something along the lines of Text File 1.txt, and if that's already made, then Txt File 2.txt, and so on.
DG stands for Date Group (not shown here, but that's because it works just fine).

k = 1

def OpenUp(k):
    try:
        f = open(dg + ' Police Report ' + str(k) + '.txt','x+')
        return i
    except:
        k += 1
        OpenUp(k)

i = OpenUp(k)
f = open(dg + ' Text File ' + str(i) + '.txt','x+')
So close... try a while loop instead of recursion, avoid the global variable, actually return the value, and... get rid of whatever i was supposed to be.
def find_next_file_num(base, ext="txt"):
    num = 1
    while True:
        try:
            with open(f"{base}{num}.{ext}") as temp:
                return num
        except FileNotFoundError as e:
            num += 1

next_num = find_next_file_num("PoliceReport_")
print(f"Next file: PoliceReport_{next_num}")