如何将此文件中的整数写入mynumbers.txt文件?

时间:2015-11-14 21:58:19

标签: python

好的,这个函数运行得很好,我只需要知道如何使它如此生成的随机整数被写入mynumbers.txt文件。

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

这是对的吗?

1 个答案:

答案 0 :(得分:0)

尝试使用append选项打开文件:outfile=Open("[FileName]", "a")然后您可以执行outfile.write(str(n) + " "),其中n是您要编写的数字。当然你可以选择除“”之外的分隔符。

或者,您可以将所有数字存储在字符串中。并在最后写下所有内容。

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)