[英]Writing random numbers to a Python file and using newline to concatenate
该程序生成用户定义数量的随机数,然后将其写入文件。 该程序可以正常工作,但是我希望文本文件使用\\ n连接。 我究竟做错了什么?
#此程序将用户定义的#随机数写入文件
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()
添加“ \\ 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()
file.write()
只是将文本写入文件。 它不会串联或附加任何内容,因此您需要自己附加\\n
。
(请注意,该类型在Python 3中将称为_io.TextIOWrapper
)
为此,只需更换
line = str(random.randint(1, 100))
与
line = str(random.randint(1, 100))+"\n"
这会将换行符附加到每个随机数。
您还可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.