Search code examples
pythonfileconcept

What does file object holds itself?


See the below code:

import os

file = open("C:/Users/AAYUSH/Desktop/file.txt", 'r' )

print(file)

for i in file:
    print(i,end="")

If I execute this code I got below output:

<_io.TextIOWrapper name='C:/Users/AAYUSH/Desktop/file.txt' mode='r' encoding='cp1252'>
This is first line!!!
This is second line!!!

My question is: If I execute print(file) then I got a dictionary of the file and when I write with the help of for loop I got inside data.

Then what actually the file object holds?


Solution

  • print(file)
    

    Invoked tke __str__ method of the file object & that happens to return a string that tells you about the type of the object i.e. TextIOWrapper & some attributes name, r etc. The file contents are not here because the file has not been read yet.

    for i in file
    

    Invoked the __iter__ method of the file object & actually does read the file (one line at a time). The file object holds a pointer to a position in the file - this is used to read from it.