0

I am making code which generates a new text file with today's date each time it is run. For exemple today's file name would be 2020-10-05. I would like to increment it so that if the program is run one or more times the same day it becomes 2020-10-05_1, _2 etc..

I have this code that I found from another question and i've tried tinkering with it but I'm still stuck. The problem is here they convert the file name to an int 1,2,3 and this way it works but this isn't the result I want.

def incrementfile():
    todayday = datetime.datetime.today().date()
    output_folder = "//10.2.30.61/c$/Qlikview_Tropal/Raport/"
    highest_num = 0
    for f in os.listdir(output_folder):
        if os.path.isfile(os.path.join(output_folder, f)):
            file_name = os.path.splitext(f)[0]
            try:
                file_num = int(file_name)
                if file_num > highest_num:
                    highest_num = file_num
            except ValueError:
                print("The file name %s is not an integer. Skipping" % file_name)
    output_file = os.path.join(output_folder, str(highest_num + 1) + f"{todayday}" + ".txt")
    return output_file

How can I modify this code so that the output I get in the end is something like 2020-10-05_0, _1, _2 etc.. ?

Thanks !

1
  • you need to store the last run time in memory by some means, probably by pickling the last run time, then check the pickle file wherever you're running the method. Commented Oct 5, 2020 at 12:09

3 Answers 3

1

I strongly recommend you to use pathlib instead of os.path.join. This is more convenient.

def incrementfile():
    td = datetime.datetime.today().date()
    path = pathlib.Path("/tmp") #set your output folder isntead of /tmp
    inc = len(list(path.glob(f"{td}*")))+1
    outfile = path/f"{td}_{inc}.txt"
    return outfile
Sign up to request clarification or add additional context in comments.

Comments

0

Not a direct answer to your question, but instead of using _1, _2 etc, you could use a full timestamp with date and current time, which would avoid duplication, EG:

from datetime import datetime

t = str(datetime.now()).replace(":", "-").replace(" ", "_")
print(t)

Example output:

2020-10-05_13-06-53.825870

Comments

0

I think this will work-

import os
import datetime

#assuming files will be .txt format

def incrementfile():

    output_folder = "//10.2.30.61/c$/Qlikview_Tropal/Raport/"


    files=os.listdir(output_folder)

    current_name=datetime.date.today().strftime('%Y-%m-%d_0')
    current_num=1


    def nameChecker(name,files):
        return True if name +'.txt' in files else False


    while namChecker(current_name,files):
        current_name+='_'+str(current_num)
        current_num+=1

    return current_name+'.txt'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.