Python File Question

I am on the course on Files, and I have a question: why can’t we just print out the actual file?

I mean, that to print out a file, you use this syntax:


But to make it much easier, why can’t you just use this syntax:


Also, I was about to ask you why the emails in the CSV file lesson were in a hash format, but then I realised that it was that way in loggers.csv, but I do want to ask you why you included hashes instead of emails.

Assuming you used something like

with open example.txt as docfile:
   content =

then docfile represents a file object and not the raw text contents of the file.
That object has a read() method that allows us to access that content.

So the question you’re asking could mean: “when opening files, why not immediately just load the content and nothing else?”.
That would be trying to conjecture the reason why it was written that way.

The simplest answer is that making it an object is more flexible for different types of operations (opening a non-text file, writing to a file, etc).


@toastedpitabread makes a good point that making an object when opening a file is more flexible.

Using a with statement to open your file also prevents you from having to close the file after the data from the file has been read. For more details, see here.

Pita, you forgot the parentheses around example.txt.

Yes thank you haha… Good catch