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

时间:2018-07-18 03:53:36

标签: python python-3.x programming-languages

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的第二位。

4 个答案:

答案 0 :(得分:2)

原因在注释中说明:

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

text=infile.readline()

此时大概是文本包含44

然后,您可以通过以下操作将其覆盖:

text = str(count)

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

答案 3 :(得分:0)

您应该先打印text的值,然后再用下一个readline覆盖它。

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

while text != "":

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