python looping through input file

后端 未结 4 1354
抹茶落季
抹茶落季 2020-12-16 15:07

My question is related to file-input in Python, using open(). I have a text file mytext.txt with 3 lines. I am trying to do two things with this fi

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 15:11

    Is there some reason you could not use the following:

    input_file = open('mytext.txt', 'r')
    count_lines = 0
    for line in input_file:
        print line
        count_lines += 1
    print 'number of lines:', count_lines
    

    The thing returned by open is a file object. File objects keep track of their own internal position as you loop over them, so in order to do what you tried first, you would have to rewind it to the beginning manually, it won't do it by itself.

提交回复
热议问题