reading a text file with python return nothing

i have a text file with some content, i need to return that content in order to print it and some update
I used he absolute path to be sure the path is correct

file = opren(r'path\to\file.txt','r')

this print( works fine, it returns the whole content. But whene i try to return the content in a form of list using print(file.readlines()) , it returns nothing; an empty list [].

my debuging was like this ,i tried to len(file.readlines()) to make sure, it is indeed return nothing, and it does. it prints 0

>Solution :

the key here is file pointer if you open you file you will notice the flashing sign.(that is your mouse cursor). after reading the content it sets the pointer at the end of your content.

  • solution 1(bad practice) : open and close after every action file.close() then opren(r'path\to\file.txt','r')

  • solution 2: change the file pointer # 0 will set the pointer at the start,then use print((file.readlines()))

Leave a Reply