随机数文件编写器

Tho*_*nes 1 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.write(line)
         print(line)

afile.close()

print("\nReading the file now." )
afile = open("Random.txt", "r")
print(afile.read())
afile.close()
Run Code Online (Sandbox Code Playgroud)

一些问题:

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

  2. 一旦打开文件就无法关闭.

  3. 读取文件时没有.

虽然我认为设置还可以,但似乎总是卡在执行上.

Vol*_*ity 5

摆脱for line in afile:,并取出其中的内容.另外,因为input在Python 3中返回一个字符串,所以将其转换为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()
Run Code Online (Sandbox Code Playgroud)

如果您担心用户可能输入非整数,则可以使用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()
Run Code Online (Sandbox Code Playgroud)

你试图做的是迭代afile,当没有时,所以它实际上没有做任何事情.