【问题标题】:Negative Integer ValuError, Append but not Write负整数值错误,追加但不写入
【发布时间】:2015-02-16 14:51:54
【问题描述】:

我的第一个问题是,当我输入 tex -10 时,除了 ValueError 不运行,只有第一个输入再次运行,但如果我输入 (-10),那么 ValuError 确实运行。我希望 ValueError 运行当我输入 -10 时,一个没有参数的负数

while True:
          try:
          number = int(input("Area?"))
       if number>0:
            break
  except ValueError: 
           print("That was not a positive number") ##

我的第二个问题是,此功能仅在我有“a”时才有效,追加,而不是在我有 Write 时,有谁知道为什么,以及如何解决它?我想写一个文件。

def list_to_file():
             file=open("file.txt","a") 
             file.write("\n")
             file.write("".join(str(lista)))

【问题讨论】:

  • break 不等于 raise exception
  • 嗯,这不是代码重复吗?我可以用另一种方式解决整个问题,你不觉得吗? @TehTris
  • 哦等等,我看看你在做什么......让我写一个答案......但是请在我写这个的时候更正你的空格。

标签: python file integer append


【解决方案1】:

对于第一个问题,听起来您想引发一个值错误,然后除此之外。

number = int(input("Area?"))
while True:
    try:
        if number > 0:
            break
        else:
            raise ValueError()
    except ValueError:
        number = int(input("Please enter a positive number"))

至于第二个问题,当它是一个小“列表”时我无法写入文件,但当它很大时能够写入。我在这里提出了问题并得到了有效的答案

Python won't write small object to file but will with large object

简而言之,当你完成写入文件时,你必须使用 file.close() 关闭文件。

def list_to_file():
     file=open("file.txt","w") 
     file.write("\n")
     file.write("".join(str(lista)))
     file.close()

因此,如果您遇到同样的问题,这应该可以解决问题。

要为每次迭代创建一个新文件,请计算每次迭代都会递增的计数,并将其发送到打印方法。然后使用该计数创建一个唯一的文件名,如下所示:

def list_to_file(count, lista):
    file=open("file_"  + str(count) + ".txt","w") 
    file.write("\n")
    file.write("".join(str(lista)))
    file.close()

allLists = list of all your listas
count = 1
for thisList in allLists:
    list_to_print(count, thisList)
    count +=1

【讨论】:

  • 感谢您!您说明了如何完美解决它:) @Malonge 您对其他问题有任何线索吗?
  • 我正在努力解决这个问题,尽管我也遇到了奇怪的麻烦。如果您觉得我的答案有用,您应该点击我的答案上的向上箭头。
  • 我正在尝试做的事情是将表写入文件,但问题是我一直在向该文件添加和添加结果,我想每次都写入它,所以我想改用“w”,但它不起作用..如果你弄清楚了,真的会超级棒!无论如何谢谢@Malonge
  • 有趣。我只是让它为我工作。澄清一下,您是要每次都更新同一个旧文件还是每次迭代都创建一个新文件?
  • 我想为每次迭代创建一个新文件,但我做不到。我只能更新同一个旧文件,我该如何解决?
【解决方案2】:

您正在格式化您的 try: except: 语句错误。它应该是这样的:

try:
    1/0
except:
    print("the exception happened")

注意 try 是如何直接在上面的,除了...在你的看起来像这样:

#your code
while True:
       try:
          number = int(input("State the number of latitudes you want to calculate energy for?"))
       if number>0:
            break
except ValueError: 
           print("That was not a positive number") ##

你有一个 except 语句,它挂在一个 while 语句下面,没有属于它的 try 语句。

您可能想要这样做的方式是这样的:

while True:
    try:
        #some sort of statement here that is going to throw an exception like 1/0 ( cant divide by zero bro )
    except:
        print("cant divide b zero bro")
        #some statement that you want to happen after the above exception is thrown
        break

除此之外,您的break 不是异常诱导语句,它所做的只是阻止循环完成。写着“break”的那一行应该写成

while True:
    try:
        if _some_sort_of_logic_not_fufilled:
            raise Exception("some exception text if you want") #you could use your ValueError here also since ValueError is derived from Exception
    except:
        print "see how it got here?"
        break # this would go here if you want it to STOP the loop after it gets the exception, or dont put break if you want it to keep going... but a while True loop... you probably wnat to eventually break out of...

【讨论】:

  • 仍然没有,按照你最后给出的例子。 @TehTris
猜你喜欢
  • 2015-04-22
  • 2017-04-02
  • 2022-09-28
  • 2019-09-15
  • 2017-10-07
  • 2020-08-30
  • 2017-05-06
  • 2015-09-08
相关资源
最近更新 更多