Search code examples
pythontxt

Saving filename in a specific format in Python


I am generating numbers in a specific range with a specific stepsize and saving to a .txt file. But I want to save the filename in a specific format. I present the current and expected output.

Start=0
End=500001
Stepsize=1000
for i in range(Start,End,Stepsize):
    #print(i)
    
    with open('All_values_{Start}_{End}_{Stepsize}.txt', 'a') as f:
        #writer = csv.writer(f)   
        #print(" =",i)
        f.writelines('\n')
        f.write(str(i))

The current output in terms of file naming is

All_values_{Start}_{End}_{Stepsize}

The expected output is

All_values_0_500001_1000

Solution

  • Use f-strings, just add an f to this line:

        with open(f'All_values_{Start}_{End}_{Stepsize}.txt', 'a') as f: