【发布时间】:2018-10-04 03:37:57
【问题描述】:
我正在编写一个程序,其中用户输入要生成的随机数的下限和上限以及要生成的随机数的数量。之后,程序将写入一个新文件“randomnum.txt”。除了写入文件之外,我的程序中的所有方面都在工作。程序完成后,“randomnum.txt”中没有写入任何值。任何帮助表示赞赏! #导入随机目录 随机导入
#Import randint function
from random import randint
#Create and open the new file
new_file = open("/Users/masonadrales/Desktop/Python
Assignments/Randomwrite:read/randomnum.txt","w")
#Get input for the amount of numbers
while (True):
try:
number_random = float(input("How many random numbers would
you like? "))
if (number_random < 0):
print("Sorry! The program only accepts positive
values.")
continue
except ValueError:
print('The value you entered is invalid. Only positive
values please!')
else:
break
#Ask for the lower limit of the random range
while (True):
try:
lower_limit = float(input("What is the lowest the random
number should be: "))
if (lower_limit < 0):
print("Sorry! The program only accepts positive
values.")
continue
except ValueError:
print('The value you entered is invalid. Only positive
values please!')
else:
break
#Ask for the higher limit of the random range
while (True):
try:
high_limit = float(input("What is the highest the random
number should be: "))
if (high_limit < 0):
print("Sorry! The program only accepts positive
values.")
continue
except ValueError:
print('The value you entered is invalid. Only positive
values please!')
else:
break
#Attempt #1 to generate (number_random) amount of random numbers
between lower and high limit
try:
for randomNumber in range(int(number_random)):
line = str(random.randint(lower_limit, high_limit))
new_file.write(line)
print(line)
except ValueError:
new_file.close()
#Print where the numbers were written to
print("The random numbers were written to randomnum.txt.")
【问题讨论】:
-
检查是否正在调用
new_file.close()。您最好使用上下文管理器 (with open(...) as new_file) 自动跟踪此情况 -
@c2huc2hu:有趣的是,只有在出现问题时才会调用它。它仍应在解释器退出时清理,但解释器中存在导致文件未刷新的错误,即使它们应该在退出时清理。