Python 我的循环和文件I/O

Python 我的循环和文件I/O,python,Python,如何让循环写入文件,直到停止循环 比如说 outFile = "ExampleFile.txt", "w" example = raw_input(" enter number. Negative to stop ") while example >= 0: example = raw_input("enter number. Negative to stop") outFile.write("The number is", example,+ "\n") 我觉得我很接近

如何让循环写入文件,直到停止循环

比如说

outFile = "ExampleFile.txt", "w"
example = raw_input(" enter number. Negative to stop ")
while example >= 0:
    example = raw_input("enter number. Negative to stop")
    outFile.write("The number is", example,+ "\n")
我觉得我很接近,但我不确定。我不知道如何在特定的环境中搜索这个问题。很抱歉,当我输入超过2个参数时,我一直收到一个错误,指出函数接受1个参数

import os.path
outFile = open("purchases.txt","w")
quantity = float(raw_input("What is the quantity of the item :"))
cost = float(raw_input("How much is each item :"))


while quantity and cost >= 0:
    quantity = float(raw_input("What is the quantity of the item :"))
    cost = float(raw_input("How much is each item :"))
    total = quantity * cost
    outFile.write("The quantity is %s\n"%(quantity))
    outFile.write("the cost of the previous quality is $s\n" %(cost))
    outFile.close()
    outFile = open("purchases.txt","a")
    outFile.write("The total is ",total)
    outFile.close()
当你写作时:

outFile = "ExampleFile.txt", "w"
创建的是
元组
,而不是
文件
对象

你可能想写:

outFile = open('ExampleFile.txt','w')
当然,您可以使用上下文管理器更好地执行此操作:

with open('ExampleFile.txt','w') as outFile:
    #...

您的代码还有第二个错误:

outFile.write("The number is", example,+ "\n")
去掉SyntaxError(
,+
),
文件。write
只接受一个参数。你可能想要这样的东西:

outFile.write("The number is {0}\n".format(example))
或使用旧样式的字符串格式(根据要求):


是的,我是故意的。我很抱歉。除此之外,它仍能做到这一点。是一个答案,还是只是让我知道?@user1861580——这次它会做一些不同的事情。看我的编辑。实际上我写的就是我想写的。这是我在计算机科学的第一年,所以当我的教授出于不同的原因做某事时,我会复制它,直到我意识到它并不总是有效。不管怎样,我知道你在那里做了什么。当你这么做的时候,它点击了更多。令人惊叹的。还有什么建议吗?您也可以使用
print
print“foo”、“bar”>>outFile
来执行此操作。或者用python3语法:
print(“foo”,“bar”,file=outFile)
你到底在那里做什么?这是指向outFile的吗?如果是,如何确保它打印在单独的行上?“\n”?对的
outFile.write("The number is %s\n"%(example))