![]() |
How to Make Unique .txt titles - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to Make Unique .txt titles (/thread-19094.html) |
How to Make Unique .txt titles - Lancaster - Jun-13-2019 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+') RE: How to Make Unique .txt titles - nilamo - Jun-13-2019 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}") |