Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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(file.read()) 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

the key here is file pointer if you open you file you will notice the flashing sign.(that is your mouse cursor).
file.read() 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

    file.seek(0) # 0 will set the pointer at the start,then use print((file.readlines()))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading