将数字写入文件python。第一个输入不打印

问题描述 投票:0回答:2

我正在将数字写入文本文件并且它可以工作,但我遇到的问题是它不会打印第一个数字。

如果我写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()
python file
2个回答
1
投票

在将第一个输入写入文件之前,您将再次提示用户。

看到这里:(我也简化了你的代码)

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

1
投票

在将第一个有效输入写入文件之前,您需要新的输入和写入。相反,首先写入有效输入然后请求输入。

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

这应该工作。

© www.soinside.com 2019 - 2024. All rights reserved.