繁体   English   中英

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

[英]Writing numbers to file python. First input doesn't print

我正在将数字写入文本文件,它可以工作,但即时通讯存在的问题是它不打印第一个数字。

如果我写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()

这应该工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM