Printing the content of the txt file

Hello!
I’m opening a file and trying 2 ways to print it content.
The way in line 3 is working.
The way in line 4 isn’t working.

Why?

1 in_data = open(from_file)
2 text_to_write = in_data.read()
3 print(f"The content of the file is:\n {text_to_write}")
4 print(f"The content of the file is:\n {in_data.read()}")

Well, if you’re running it in the same script, it wouldn’t work because when you read it, the file object points to the end of the file, so nothing is returned. To fix that, you have to put in in_data.seek (0) before the 4th line so that it will again point to the beginning of the file.

If you have more questions, refer the Python documentation.

1 Like

Looks @Zayed has the right answer. Seek it back to the beginning and you can read it again. Or close it and reopen it.

1 Like

Great! Now i understand how it works better.
Thanks!