How do I create a incrementing filename in Python?

后端 未结 12 2064
终归单人心
终归单人心 2020-11-28 05:45

I\'m creating a program that will create a file and save it to the directory with the filename sample.xml. Once the file is saved when i try to run the program again it over

12条回答
  •  感情败类
    2020-11-28 06:17

    Here is one more example. Code tests whether a file exists in the directory or not if exist it does increment in the last index of the file name and saves The typical file name is: Three letters of month_date_lastindex.txt ie.e.g.May10_1.txt

    import time
    import datetime
    import shutil
    import os
    import os.path
    
    
    da=datetime.datetime.now()
    
    data_id =1
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime("%b%d")
    data_id=str(data_id)
    filename = st+'_'+data_id+'.dat'
    while (os.path.isfile(str(filename))):
        data_id=int(data_id)
        data_id=data_id+1
        print(data_id)
        filename = st+'_'+str(data_id)+'.dat'
        print(filename)
    
    
    shutil.copyfile('Autonamingscript1.py',filename)
    
    f = open(filename,'a+')
    f.write("\n\n\n")
    f.write("Data comments: \n")
    
    
    f.close()
    

提交回复
热议问题