reading a text file with python return nothing

Question:

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

file = open(r'pathtofile.txt','r')

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

my debugging was like this, I tried len(file.readlines()) to make sure, it is indeed returning nothing, and it does. It prints 0

Asked By: jackdoli64

||

Answers:

the key here is file pointer
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'pathtofile.txt','r')

  • solution 2: change the file pointer

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

Answered By: Ayb009

So it should look something like this::

filename = "this/is/a/file"

with open(filename, "r") as file:
   lines_list = file.read_lines()

print(lines_list)

Just in case you don’t know, you don’t need to manually close the file when you use with. So that’s why it’s missing above.

Also, based on Ayb009’s answer it just seems like you tried to read again without closing the file which would start from the last character read + 1. The solution here skips that issue entirely by letting you do whatever you want with the lines without needing to keep the file open.

Answered By: jake.csc
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.