我正在使用bin编号编写Python代码,然后创建像这样的数字列表
bin = "377731"
range(00000, 99999)
for i in range(len(bin)):
target = open('{0}.txt'.format(bin), 'a') ## a will append, w will over-wri$
target.write("{0}{1}000".format(bin,i) + "\n")
target.close()
Python这样显示列表的问题
3777311000
我需要像这样写
3777310000100
脚本在达到数字5后也停止
有什么帮助吗?
谢谢
最佳答案
您的代码中有几件事需要更改:
您已将bin
定义为具有值377731
的字符串。该字符串的长度为6,这就是循环在5后停止的原因。
另外,bin
是python中的内置函数,因此最好不要将其用作变量的名称。
在循环中打开和关闭文件实在是太过分了。
尝试以下方法:
bin_suffix = "377731"
target = open('{0}.txt'.format(bin_suffix), 'a') ## a will append, w will over-wri$
for i in range(99999):
target.write('{}{}'.format(bin_suffix, str(i).zfill(7)) + "\n")
target.close()
zfill
是一个字符串函数,使用零填充字符串的指定长度。在您的情况下,377731
后需要7位数字,因此您将7指定为zfill
的参数希望这可以帮助。