将随机数写入Python文件并使用换行符连接

时间:2013-12-11 20:07:08

标签: python file-io newline

该程序生成用户定义的随机数量,然后写入文件。该程序编写正常,但我希望文本文件使用\ n来连接。我做错了什么?

#This程序写入用户定义的     #random number to a file

import random

randfile = open("Randomnm.txt", "w" )

for i in range(int(input('How many to generate?: '))):
    line = str(random.randint(1, 100))
    randfile.write(line)
    print(line)

randfile.close()

3 个答案:

答案 0 :(得分:4)

添加“\ n”:

import random

randfile = open("Randomnm.txt", "w" )

for i in range(int(input('How many to generate?: '))):
    line = str(random.randint(1, 100)) + "\n"
    randfile.write(line)
    print(line)

randfile.close()

答案 1 :(得分:1)

file.write()只是将文本写入文件。它不会连接或附加任何内容,因此您需要自己附加\n

(请注意,该类型将在Python 3中称为_io.TextIOWrapper

为此,只需替换

即可
line = str(random.randint(1, 100))

line = str(random.randint(1, 100))+"\n"

这将为每个随机数附加一个换行符。

答案 2 :(得分:1)

您还可以使用Python 3的print函数的file关键字参数:

import random

with open("Randomnm.txt", "w") as handle:
    for i in range(int(input('How many to generate?: '))):
        n = random.randint(1, 100)

        print(n, file=handle)
        print(n)

# File is automatically closed when you exit the `with` block