Ok this function works perfectly, I just need to know how do i make it so it so the random integers that are generated, are written to the mynumbers.txt file.
def main():
#Open a file for writing
outfile = open ('mynumbers.txt' , 'w')
#Generate random integer number
from random import randint
number = randint(6, 12)
print("Write will create", number, "random numbers")
import random
i = 0
while i < 11:
# Get random number in range 10 through 20.
n = random.randint(10, 20)
print(n)
i += 1
#Write the numbers to the file
foo = ""
while (i):
#find n
foo += str(n) + " "
outFile.write(foo)
#Call the main function
main()
Is this right?
Try opening the file with the append option instead: outfile=Open("[FileName]", "a")
Then you can do a outfile.write(str(n) + " ")
where n is the number you wish to write. Of course you can pick a deliminator other than " ".
Alternatively, you could store all of the numbers in a string. And write them all at the end.
foo = ""
while (looping):
#find n
foo += str(n) + " "
outFile.write(foo)
===REVISED===
import random
output = ""
deliminator = "\n" #Put a line-break after each number
filepath = "mynumbers.txt"
i = 0
while i < 11:
# Get random number in range 10 through 20.
n = random.randint(10, 20)
print(n) #is this necessary?
i += 1
output += str(n) + deliminator
#Write the numbers to the file
with open(filepath, 'w') as file:
file.write(output)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句