简体   繁体   English

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

[英]Writing random numbers to a Python file and using newline to concatenate

This program generates a user defined amount of random numbers and then writes to a file. 该程序生成用户定义数量的随机数,然后将其写入文件。 The program works fine as written, but i want the text file use \\n to concatenate. 该程序可以正常工作,但是我希望文本文件使用\\ n连接。 What am I doing wrong? 我究竟做错了什么?

#This program writes user defined #random numbers 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()

Add "\\n": 添加“ \\ 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() simply writes text to a file. file.write()只是将文本写入文件。 It does not concatenate or append anything, so you need to append a \\n yourself. 它不会串联或附加任何内容,因此您需要自己附加\\n

(Note that the type would be called _io.TextIOWrapper in Python 3) (请注意,该类型在Python 3中将称为_io.TextIOWrapper

To do this, simply replace 为此,只需更换

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

with

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

This will append a newline to every random number. 这会将换行符附加到每个随机数。

You could also make use of Python 3's print function's file keyword argument: 您还可以使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM