-2

This may be rudimentary question for some and not even a programming one technically but I just stumble upon a thought process which I could not find an answer myself.

As we all know file handling operations are one of the important aspect of the programming and it is also one of the painful aspect if not used carefully specially closing the open file objects.

for example we have at least two ways of file handling ways (using python for simplicity purpose)

f = open("file.txt", "r")
content = f.read()
f.close() # does not executes, in case of exception

Or more safer approach using context manager like

with open("file.txt", "r") as f:
     content = f.read()
# No need to worry about file closing

We can all can agree that the approach using context manager "with" is always better approach. This made me wonder why the first approach is even permitted.

I agree that all languages change and improve throughout time. And there are numerous examples of how, in newer versions, the language may stop supporting some of the old functions, classes, and so on, or at the very least give an alert that the way has been decrypted and will no longer be supported in future versions.

I would appreciate some explanations, as well as any references that I may go into in order to better comprehend  the concept.

DoctorAV
  • 1,189
  • 1
  • 14
  • 40
  • 1
    `with` was introduced in 2005 https://peps.python.org/pep-0343/ so you couldn't do this before. It adds enter and exit around existing things, so you can still use them "raw". Maybe a bad choice, but it is what it is – doctorlove Aug 25 '23 at 12:56
  • 1
    This shouldn't have the C# tag. Also, the `with` method does not allow you to close the file in another place (eg. from another function). There are plenty of reasons why you would want to do this. As @doctorlove pointed out, `with` is a later addition and removing (the perfectly working) `f.close()` method would break countless programs for no reason – John Aug 25 '23 at 12:59
  • 1
    While there is a `with` keyword in C#, it's not about file handling or some such: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression – EyesShriveledToRaisins Aug 25 '23 at 13:00
  • 1
    You're looking for the `using` statement, and C# can enforce this using an analyzer warning – Charlieface Aug 25 '23 at 13:03
  • @doctorlove I understand that "with" has been introduced later on. My question was why not restrict the uses of the other approach. But as John pointed out there are plenty of reasons where we want to open the file across the functions which may not be possible with "with". Now come to think about it, it seems to be my brain fog moment NGL.. :) – DoctorAV Aug 25 '23 at 13:04
  • @Charlieface You are right, thanks. Did not know about analyzer though will explore about it. – DoctorAV Aug 25 '23 at 13:06

0 Answers0