【问题标题】:Random number file writer and read随机数文件写入和读取
【发布时间】:2015-11-02 23:32:27
【问题描述】:

说明

编写一个程序,将一系列随机数写入文件。

  1. 为每次执行生成的数字计数将为 随机介于 1 到 20 之间。

  2. 生成的实际数字将是介于 1 和 100

  3. 程序的每次运行都会显示一条消息,指示 写入文件的新数字数

  4. 程序的每次运行都会显示一条消息,指示 从文件中读取的记录数

  5. 您无法计算或假设知道 文件。使用带循环的截止日期方法到EOF

  6. 您的文件读取和文件写入都必须是函数(2 个函数, 每个一个),每个都从 main 调用。

  7. 首次写入文件时必须使用w 模式和a 或 之后每次w模式。

  8. 用户将决定是追加到现有文件还是写入新文件 文件。

这就是我所拥有的

import random

def main():
        more = 'y'

        while more.lower() == 'y':

                random_numbers = open('Unit 4 numbers.txt', 'w')
                NumtoBeWr = random.randint(1, 20)
                print(NumtoBeWr, 'numbers added to output file: ')

                for count in range(NumtoBeWr):
                      number = random.randint(1, 100)
                      print(number)
                      random_numbers.write(str(number) + '\n')

                random_numbers.close()

                random_numbers = open('Unit 4 numbers.txt', 'r')


                # This the code to read the file

                line = random_numbers.readline()
                number = 0
                total = 0

                while line != " ":
                        number = int(line)

                        line = line.rstrip('\n')
                        print(number)
                        total = total + int(line)
                        number = number + number
                        line = random_numbers.readline()

                        print("The total of the numbers: "+ str (total))
                        print("Total count of numbers read from file: "+ str (number))
                        more = input("Do you want to run again to write and read more numbers. (Y/N): ")
                random_numbers.close()

        print("Thank for using this program")


main()

我遇到的一些问题

  1. 不是把所有数字加在一起
  2. 不是把所有的数字加在一起

完成程序的示例输出应如下所示:

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    你应该更新你的while循环如下:

    while line:
        number += int(line)
        total += 1
        line = random_numbers.readline().rstrip("\n")
    
    print("The total of the numbers: " + str(total))
    print("Total count of numbers read from file: " + str(number))
    more = input("Do you want to run again to write and read more numbers. (Y/N): ")
    

    也就是说,您应该将总计数的打印放在循环之外。此外,您应该将total 加一而不是当前行中的数字以获取生成的总数。

    【讨论】:

    • 我已经更新了 while 循环,它将它们的数字相加并计算它们。但是当我输入“y”以“写入和读取更多数字”时,它如何不将旧数字计入新数字。我的问题是,当你输入“y 让它写入和读取更多数字”时,你如何让它用新数字计算旧数字。就像示例文件中的那个一样。首先它添加了 52,第二次打印 52 并添加了 39,并且从文件中读取的总数为 2。
    • 将初始化(分配给0)放在第一个while 循环之外。
    • 嘿,我按照你说的做了,但它不起作用。我的分配编号也为 0 和总数,但它仍然没有将旧编号写入和读取到新编号。相反,如果我输入“y”,它只是写入和读取数字,而不包括旧数字和数字数字,甚至用新数字计算它们。请你告诉我怎么做,好吗?
    猜你喜欢
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 2016-06-07
    • 2021-10-12
    相关资源
    最近更新 更多