Search code examples
pythonstringstring-formattingcycle

Very simple python cycle string


I want to write in a file which changes the name with the counter.

for j in range(30):
    fileout.write("bla bla")

and fileout should be

file001 if j=1

file002 if j=2

...

...

I cannot format it in the right way. Anyone can help me? Thank you


Solution

  • You can try to use the .zfill( < number of digits > ) option. It will complet your string with 0.

    For example, this code should work :

    radical ='file'                                                                                                                          
    numberOfDigits = 3                                                                                                                          
    
    for j in range( 30 ) :                                                                                                                   
        fileout = open ( radical + '%s' %(str(j).zfill(numberOfDigits)) + '.txt' , 'w' )                                                        
        fileout.write('bla bla')                                                                                                             
        fileout.close()