在停止循环之前,如何让循环写入文件?
例如
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()
答案 0 :(得分: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")
baring SyntaxError(,+
),file.write
只接受1个参数。你可能想要这样的东西:
outFile.write("The number is {0}\n".format(example))
或使用旧式字符串格式(根据要求):
outFile.write("The number is %s\n"%(example))