【发布时间】:2015-11-02 23:32:27
【问题描述】:
说明
编写一个程序,将一系列随机数写入文件。
为每次执行生成的数字计数将为 随机介于 1 到 20 之间。
生成的实际数字将是介于 1 和 100
程序的每次运行都会显示一条消息,指示 写入文件的新数字数
程序的每次运行都会显示一条消息,指示 从文件中读取的记录数
您无法计算或假设知道 文件。使用带循环的截止日期方法到
EOF。您的文件读取和文件写入都必须是函数(2 个函数, 每个一个),每个都从 main 调用。
首次写入文件时必须使用
w模式和a或 之后每次w模式。用户将决定是追加到现有文件还是写入新文件 文件。
这就是我所拥有的
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()
我遇到的一些问题
- 不是把所有数字加在一起
- 不是把所有的数字加在一起
完成程序的示例输出应如下所示:
【问题讨论】:
标签: python python-3.x