0

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

例如

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()
4

1 回答 1

0

当你写:

outFile = "ExampleFile.txt", "w"

你创建一个tuple,而不是一个file对象。

你可能打算写:

outFile = open('ExampleFile.txt','w')

当然,您可以使用上下文管理器做得更好:

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

您的代码有第二个错误:

outFile.write("The number is", example,+ "\n")

暴露 SyntaxError ( ,+),file.write只需要 1 个参数。你可能想要这样的东西:

outFile.write("The number is {0}\n".format(example))

或使用旧样式的字符串格式(根据要求):

outFile.write("The number is %s\n"%(example))
于 2012-11-29T07:31:38.417 回答