将数字写入文件python。第一个输入不打印
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将数字写入文件python。第一个输入不打印相关的知识,希望对你有一定的参考价值。
我正在将数字写入文本文件并且它可以工作,但我遇到的问题是它不会打印第一个数字。
如果我写1 2 3 4 5 6然后我有一个哨兵循环并使用-1结束。
它将打印2 3 4 5 6
outfile = open("userInput.txt","w")
userInput = int(input("Enter a number to the text file: "))
count = 0
if int(userInput) != -1:
while(userInput) !=-1:
userInput = int(input("Enter a number to the text file: "))
outfile.write(str(userInput) + "\n")
count+=1
if count == 0:
print("There is no numbers in the text file")
outfile.write("There is no numbers in the text file")
count+=1
outfile.close()
答案
在将第一个输入写入文件之前,您将再次提示用户。
看到这里:(我也简化了你的代码)
outfile = open("userInput.txt","w")
userInput = int(input("Enter a number to the text file: "))
count = 0
while(userInput !=-1): # You don't need the if, because if userInput == -1, this while loop won't run at all
outfile.write(str(userInput) + "\n") # Swapped these lines so that it would write before asking the user again
userInput = int(input("Enter a number to the text file: "))
count+=1
if count == 0:
print("There is no numbers in the text file")
outfile.write("There is no numbers in the text file")
outfile.close()
另一答案
在将第一个有效输入写入文件之前,您需要新的输入和写入。相反,首先写入有效输入然后请求输入。
outfile = open("userInput.txt","w")
userInput = int(input("Enter a number to the text file: "))
count = 0
while(userInput != -1)
outfile.write(str(userInput) + "\n")
userInput = int(input("Enter a number to the text file: "))
count+=1
if count == 0:
print("There is no numbers in the text file")
outfile.write("There is no numbers in the text file")
outfile.close()
这应该工作。
以上是关于将数字写入文件python。第一个输入不打印的主要内容,如果未能解决你的问题,请参考以下文章
写入另一个python程序raw_input而不会弹出一个新的黑屏