Python Forum
How to Make Unique .txt titles
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to Make Unique .txt titles
#1
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+')
Reply
#2
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}")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Extracting Reoccuring Row Titles Hier0phant 1 1,971 Nov-09-2018, 02:46 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020