I want to generate sequential numbers using python and save them in .txt document, but I have not been able to generate numbers in the format I want.
The format I want:
(000,000,000)
(000,000,001)
(000,000,002)
(000,000,003)
...
(000,000,100)
...
(000,001,000)
...
(001,000,000)
...
(100,000,000)
...
(255,255,255)
Note: Numbers must be between 0-255.
My code:
file = open("numbers.txt","w")
numbers = [i for i in range(256)]
file.write(numbers)
file.close()
CodePudding user response:
You could simply so this with three nested loops:
for a in range(256):
for b in range(256):
for c in range(256):
print("(i,i,i)" % (a,b,c))
Note the formatting for leading zeros. And there are the itertools
for a more efficient way:
import itertools
for item in itertools.product(range(256), repeat=3):
print("(i,i,i)" % item)
CodePudding user response:
This'll do what you want. Note that this produces a pretty large file (there are 256^3 possible values, more than 16 million).
import itertools
with open("numbers.txt", "w") as f:
for color in itertools.product(range(256), repeat=3):
f.write("({:03d}, {:03d}, {:03d})\n".format(*color))
Note that you should use a with
block context manager to read from and write to files, as it automatically closes the files afterwards.