简体   繁体   English

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

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

i'm writing numbers to a text file and it works but the issue im having is that it doesn't print the first number. 我正在将数字写入文本文件,它可以工作,但即时通讯存在的问题是它不打印第一个数字。

If I writing 1 2 3 4 5 6 then I have a sentinel loop and use -1 to end. 如果我写1 2 3 4 5 6,那么我有一个哨兵循环,并使用-1结束。

It would print 2 3 4 5 6 它会打印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()

You are prompting the user a second time before you write the first input to the file. 在将第一个输入写入文件之前,您是在第二次提示用户。

See here: (I also simplified your code a little) 参见此处:(我也简化了您的代码)

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

You're asking for new input and writing that before you write the first valid input to the file. 您需要新的输入并在将第一个有效输入写入文件之前将其写入。 Instead, write the valid input first and then ask for input. 相反,请先输入有效输入,然后再要求输入。

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

This should work. 这应该工作。

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

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