What does it mean by a file object when using 'with open('filename') as new_name:

i want to know what is meant by a file object is the file object the contents of a file i want to know whats contained in the file object

That’s a good question, from the docs:
Text I/O expects and produces str objects. This means that whenever the backing store is natively made of bytes (such as in the case of a file), encoding and decoding of data is made transparently as well as optional translation of platform-specific newline characters.

Note this is specifically for files with text in them. You can also open different flavors of binary files (buffered and unbuffered).

This is enough information to go down rabbit holes with. But feel free to ask follow-ups.


1 Like

thanks man any simpler way of describing it i’m self learning so i’m not caught up with all terminology

Yes, sure no problem. I’ll try to give a high level explanation that is simpler but still tries to answer your question, and a more involved one so you have a taste of what is going on.

The simple way:
We need an intermediate space for your file to be modified quickly and safely (no file corruption). The file object is a sort of handle into that intermediate space that lets us do that. It allows you to do read and write operations on a given file. It is not the actual file, but an interface that let’s us do things with the file.

The slightly more involved explanation:

From the operating systems perspective:
We have files in our computer. In memory they are all encoded in binary, but many can be read in human-readable text. They each have their location in some sort of hard disk storage that when you turn the computer on and off it still persists.

From an architecture perspective, for the CPU it would take too long to access the hard disk directly (the CPU is the core of the computer that does the actual “computing” and heavy operations).

Instead it accesses RAM (random access memory, don’t worry about the name). Working back and forth between the CPU and RAM is super quick in comparison to the hard disk. The important part is that because of this, we want to load a text file into RAM before we do operations on it. This essentially means copying the contents of the file into RAM for reading/writing. If we write, that means we need to copy the new contents back.

The actual details are more nuanced but that’s the high level of it, give or take.


thanks man i understood it much better