【问题标题】:random integers reading and writing a file. Attempting to create multiple functions using a range 0,501随机整数读取和写入文件。尝试使用范围 0,501 创建多个函数
【发布时间】:2021-02-13 11:15:23
【问题描述】:

我正在为班级做一些 Python 作业,我无法回答这个问题。我在我的代码中找不到错误。我收到的错误是TypeError: 'function' object is not iterable。问题是:

一个。随机数文件写入功能 编写一个函数,将一系列随机数写入名为“random.txt”的文件中。每个随机数应该在 1 到 500 的范围内。函数应该接受一个参数,告诉它要写入文件的随机数。

b。随机数文件阅读器功能 编写另一个函数,从文件“random.txt”中读取随机数,显示数字,然后显示以下数据:

总数

从文件中读取的随机数个数

c。主功能 编写一个主函数,询问用户想要生成多少个随机数。他们在a中调用函数。将用户想要的数字作为参数并生成随机数以写入文件。接下来调用b中的函数。

这是我的代码:

import random
def random_Write(num):
# Open a file  for writing 
    file_w = open('random.txt', 'w')
       
    for i in range(0,num):
        rand = random.randrange(1,501)
        file_w.write(str(rand) + '\n')
        #closing file
    file_w.close()
        
def random_Read():
# Reading from file
    readFile = open('random.txt', 'r')
    count = 0
    total = 0
    for lines in random_Read:
        count +=1
        total += float(lines)

        print ('number count: ', str(count))
        print ('The numbers add up to: ', str(total))
        readFile.close()

def main():
    num = int(input("How many numbers would you like to generate?: "))
    random_Write(num)
    random_Read()

main()

【问题讨论】:

  • 您的错误在这一行:for lines in random_Read:random_read 是一个函数(您已定义)但您正在循环它。在for循环中in前面,应该放一个列表或者一个可迭代对象。
  • 您好,非常感谢。我已经调整了该代码,但现在我收到错误“对已关闭文件的 I/O 操作”。
  • 是的。您需要从文件中读取行()。
  • 谢谢阿明,感谢您的帮助。代码现在运行!

标签: python python-3.x function random range


【解决方案1】:

实际上很简单,在 random_Read() 中,在 for 循环中,而不是 for lines in random_Read: 放入 for lines in readFile.readlines(): 为什么会出现错误?因为一个简单的错字,因为你说 random_Read 是函数...

【讨论】:

    【解决方案2】:

    您的函数 random_Read 有一些错误。这是一个更正的版本:

    def random_Read():
    #Reading from file
        readFile = open('random.txt', 'r')
        count = 0
        total = 0
        #You were looping with random_Read. I changed to readFile.readlines()
        #so you get a list with all of the lines of the file.
        for lines in readFile.readlines():
            count +=1
            total += float(lines)
            print ('number count: ', str(count))
            print ('The numbers add up to: ', str(total))
        #only call .close() once, at he end of the function
        readFile.close()
    

    【讨论】:

    • 没问题,@Tim!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多