很简单python循环字符串

Very simple python cycle string

我想写入一个用计数器更改名称的文件。

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

fileout应该是

file001 如果 j=1

file002 如果 j=2

...

...

我无法以正确的方式格式化它。 任何人都可以帮助我吗? 谢谢

不确定以下内容是否符合您的需要? 下面的代码将创建 file000 - file029 with 'bla bla' inside

for i in range(30):
    with open("file%03d" % i, 'w') as f:
        f.write('bla bla')

您可以尝试使用.zfill( <位数> ) 选项。它将用 0.

完成您的字符串

例如,这段代码应该有效:

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()