I want to iterate serial numbers from 000 to 999 in Python and save them to a txt file
import os
os.system ('clear')
lis9 = 01000
while lis9 < 01099 :
lis9 = lis9 1
print (lis9)
How do I start from a specific number and end at a specific number? The numbers start from zero
Each number begins on a new line
For example
01000
01001
.
01010
.
.
01099
CodePudding user response:
Use f
string
with open('out.txt','w') as f:
for n in range(0,1000):
f.write(f'{n:03}\n')
output ('out.txt')
000
001
002
003
...
996
997
998
999
CodePudding user response:
I like one liners for this kind of thing myself:
print([str(x)[-3:] for x in range(1000,2000)], sep="\n", file=open("out.txt","w"))
CodePudding user response:
The function range()
can serve your goal:
https://docs.python.org/3/library/functions.html#func-range
You can use it by range(1000)
and then going through it by:
for i in range(1000):
print(i)
And it would print line by line from 0 to 999.
If you want the number to be 000 and not 0, (086 instead of 86 etc) you can use print(f"{i:0>3}")
CodePudding user response:
with open("file.txt", "w") as f:
f.writelines("\n".join([f"{x:03}" for x in range(1000)]))