【问题标题】:Trouble with Getting Values to Write to File将值写入文件时遇到问题
【发布时间】: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:有趣的是,只有在出现问题时才会调用它。它仍应在解释器退出时清理,但解释器中存在导致文件未刷新的错误,即使它们应该在退出时清理。

标签: python random


【解决方案1】:

您的问题实际上是在写入文件之前。

您在line = str(random.randint(lower_limit, high_limit)) 行中调用了random.randint,而实际上您只在顶部导入了randint。只需将其更改为 line = str(randint(lower_limit, high_limit)) 即可。

改变那一行使你的代码工作:

#Import randint function
from random import randint

#Create and open the new file
new_file = open("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(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.")

示例会话:

How many random numbers would you like? 7
What is the lowest the random number should be: 4
What is the highest the random number should be: 7
5
5
7
4
4
6
7
The random numbers were written to randomnum.txt.

randomnum.txt 的内容:

5574467

如果您希望每次在新行上打印数字,只需将输出写入的那一行更改为:

new_file.write(line + '\n')

【讨论】:

  • 我尝试实施您建议的修复程序,但我的文件仍然没有真正写入文件“randomnum.txt”。还有其他可能的错误吗?
  • 文本文件是被创建然后没有被写入,还是根本没有被创建?如果你的目录中有它,删除它,然后运行代码,看看它是否是由代码创建的,然后它是否包含任何输出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-12
  • 1970-01-01
  • 2021-11-27
相关资源
最近更新 更多