TypeError:仅在写入文件时不支持打印时

时间:2016-07-16 19:53:54

标签: python typeerror writefile

我已经编写了一些代码(下面),这些代码工作正常,直到我添加一个语句将其写入文件。

我得到的错误是TypeError:不支持的操作数类型为%:'NoneType'和'float'出现在第43行。

令我困惑的是,当我使用完全相同的语句仅在我写时才打印时,它不会抛出此错误。我已经通过这个错误查看了其他人,但无法解决我的情况下发生的事情。

我试图通过每一行来分解它,看看它是否通过每个写语句普遍存在。

如果有人能指出我正确的方向,那将非常感谢。

import time

timeOfday = int((time.strftime("%H")))

if timeOfday < 11:
    meal = "Breakfast"
elif timeOfday >=11 and timeOfday <= 5:
    meal = "Lunch"
else:
    meal = "Dinner"

fileName = meal + " " + (time.strftime("%d%m%Y")) +".txt"

print "Hello, Please let us know how much your bill was"
billAmount = float(raw_input(">>"))

print "How much would you like to tip?"
tipAmount = float(raw_input(">>"))

print "How many people are paying?"
peopleAmount = float(raw_input(">>"))

if tipAmount > 1:
    tipAmount = tipAmount / 100

billAndTip = ((billAmount*tipAmount)+billAmount)
finalTip = (billAmount * tipAmount)
billDivided = (billAndTip / peopleAmount)

print "The total bill is %r" % (billAndTip)
print "Of which %r is the tip" % (finalTip)

if peopleAmount == 1:
    print"Looks like you are paying on your own"

else:

    print "Each Person is paying: %r" % (billDivided) 


target = open(fileName, 'w')
# target.write("The bill was %r before the tip \n You tipped %r% \n The total bill was %r \n Split between %r people it was %r each") % (billAmount, tipAmount*100, billAndTip, peopleAmount, billDivided)
target.write("The bill was %r before the tip") % (billAmount)
target.write("\n")
target.write("You tipped %r%") % (tipAmount)
target.write("\n")
target.write("The total bill was %r") % (billAndTip)
target.write("\n")
target.write("Split between %r people it was %r each") % (peopleAmount, billDivided) 
target.close()

print "This info has now been saved for you in the file %r" % (fileName)

2 个答案:

答案 0 :(得分:0)

我认为你需要通过将%符号转换为双倍 - %:

target.write("The bill was %r before the tip \n You tipped %r%% \n The total bill was %r \n Split between %r people it was %r each") % (billAmount, tipAmount*100, billAndTip, peopleAmount, billDivided)

(注意"You tipped %r%% \n"。)

@LPK指出了一个更大的问题。每条线都是这样的:

target.write("You tipped %r%") % (tipAmount)

需要这样:

target.write("You tipped %r%" % (tipAmount))

答案 1 :(得分:0)

target.write("The bill was %r before the tip") % (billAmount)

您正在使用%运算符,结果为target.write(...)target.write(...)会返回None,这就是错误说出来的原因。

据推测,您希望在将传递给target.write(...)之前将帐单金额插入字符串中。那样做吧!

target.write("The bill was %r before the tip" % (billAmount))

换句话说,因为你想在写之前进行插值,所以它会在括号内进行写调用。