为什么我的程序不读取引用文件(文件名)中的第一行代码?

Why is my program not reading the first line of code in the referenced file(fileName)?

def main():
    read()

def read():

    fileName=input("Enter the file you want to count: ")

    infile=open(fileName , "r")
    text=infile.readline()
    count=0
    while text != "":

        text=str(count)     
        count+=1
        text=infile.readline()



        print(str(count)+ ": " + text)

    infile.close()     
main()

-引用的.txt文件只有两个元素

44

33

-这段代码的输出应该类似于

1:44

2:33

-我的输出是

1:33

2:

我不确定为什么程序没有选择引用的 .txt 文件中的第一行。行号是正确的,但是 33 应该排在 44 之后。

我对你的阅读功能很困惑。您首先将第一行读入文本:

text=infile.readline()

推测此时文本包含44

然后,您可以在对该值进行任何操作之前通过覆盖它来立即删除该值:

text = str(count)

即您在打印任何内容之前阅读了两行。

原因在评论中说明:

def main():
    read()

def read():
    fileName=input("Enter the file you want to count: ")
    infile=open(fileName , "r")
    text=infile.readline()  ##Reading the first line here but not printing
    count=0
    while text != "":
      text=str(count)     
      count+=1
      text=infile.readline() ##Reading the 2nd line here
      print(str(count)+ ": " + text) ##Printing the 2nd line here, missed the first 
                                     ##line

    infile.close()     


main()

修改程序为:

def main():
   read()

def read():
   fileName= input("Enter the file you want to count: ")
   infile = open(fileName , "r")
   text = infile.readline()
   count = 1                             # Set count to 1
   while text != "":
      print(str(count)+ ": " + str(text))   # Print 1st line here
      count = count + 1                     # Increment count to 2 
      text = infile.readline()              # Read 2nd line 

   infile.close()                           # Close the file


main()

在用下一个 readline 覆盖它之前,您应该打印 text 的值。

只需将print语句移动到readline之前:

while text != "":

    count+=1
    print(str(count)+ ": " + text)
    text=infile.readline()
def main():
    read()

def read():

    fileName=input("Enter the file you want to count: ")

    with open(fileName,'r') as f:
        print('\n'.join([' : '.join([str(i+1),v.rstrip()]) for i,v in enumerate(f.readlines())]))
main()