Python 随机数文件编写器

Python 随机数文件编写器,python,random,numbers,Python,Random,Numbers,说明: 编写一个将一系列随机数写入文件的程序 每个随机数应在1到100之间 应用程序应该让用户指定文件将包含多少随机数 以下是我所拥有的: import random afile = open("Random.txt", "w" ) for line in afile: for i in range(input('How many random numbers?: ')): line = random.randint(1, 100) afile

说明:

  • 编写一个将一系列随机数写入文件的程序
  • 每个随机数应在1到100之间
  • 应用程序应该让用户指定文件将包含多少随机数
以下是我所拥有的:

import random

afile = open("Random.txt", "w" )

for line in afile:
    for i in range(input('How many random numbers?: ')):
         line = random.randint(1, 100)
         afile.write(line)
         print(line)

afile.close()

print("\nReading the file now." )
afile = open("Random.txt", "r")
print(afile.read())
afile.close()
有几个问题:

  • 它不是根据用户设置的范围在文件中写入随机数

  • 文件打开后无法关闭

  • 当文件被读取时,没有任何内容


  • 虽然我认为设置还可以,但它似乎总是在执行时卡住。

    去掉文件中的
    行:
    ,然后取出其中的内容。另外,因为在Python3中,
    input
    返回一个字符串,所以首先将其转换为
    int
    。当你必须写一个字符串时,你正试图将一个整数写入一个文件

    它应该是这样的:

    afile = open("Random.txt", "w" )
    
    for i in range(int(input('How many random numbers?: '))):
        line = str(random.randint(1, 100))
        afile.write(line)
        print(line)
    
    afile.close()
    
    如果担心用户可能输入非整数,可以使用
    try/except

    afile = open("Random.txt", "w" )
    
    try:
        for i in range(int(input('How many random numbers?: '))):
            line = str(random.randint(1, 100))
            afile.write(line)
            print(line)
    except ValueError:
        # error handling
    
    afile.close()
    

    您试图做的是迭代
    afile
    的行,但没有,所以它实际上什么都没有做。

    去掉
    for line in afile:
    ,并取出其中的内容。另外,因为在Python3中,
    input
    返回一个字符串,所以首先将其转换为
    int
    。当你必须写一个字符串时,你正试图将一个整数写入一个文件

    它应该是这样的:

    afile = open("Random.txt", "w" )
    
    for i in range(int(input('How many random numbers?: '))):
        line = str(random.randint(1, 100))
        afile.write(line)
        print(line)
    
    afile.close()
    
    如果担心用户可能输入非整数,可以使用
    try/except

    afile = open("Random.txt", "w" )
    
    try:
        for i in range(int(input('How many random numbers?: '))):
            line = str(random.randint(1, 100))
            afile.write(line)
            print(line)
    except ValueError:
        # error handling
    
    afile.close()
    

    您试图做的是在没有文件的情况下,遍历
    afile
    ,因此它实际上什么也没做。

    感谢您的回复,当我运行代码时,我得到了这个错误文件“C:/Users/Owner/Desktop/ei8069_Assignment_Q1.py”,第19行,在文件中写入(行)类型错误:应为字符缓冲区对象我该怎么办?似乎它没有像我想要的那样写入文件…感谢您的回复,当我运行代码时,我得到了这个错误文件“C:/Users/Owner/Desktop/ei8069_Assignment_Q1.py”,第19行,在afile.write(line)中TypeError:需要字符缓冲区对象我该怎么办?似乎它没有像我想要的那样写入文件。。。。