Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

6
  • 11
    Just a small addition, to use the with statement in Python 2.5 you need to add "from future import with_statement". Other than that, opening files with the with statement is definitely more readable and less error-prone than manual closing. Commented Sep 24, 2008 at 6:48
  • 2
    You might consider the fileinput helper lib with handles the dirty open/read/modify/write/replace routine nicely when using the inline=True arg. Example here: stackoverflow.com/a/2363893/47390 Commented Feb 1, 2012 at 21:14
  • 7
    It's not a style I use, D.Rosado, but when using the with style, I don't think you need to manually close. The with keeps track of the resource it creates. Commented May 14, 2012 at 17:47
  • 10
    You do not need to manually close the file. That's the whole point of using "with" here. (Well, actually, Python does this as soon as the file object is garbage collected, which in CPython happens when the name bound to it goes out of scope... but other implementations don't, and CPython might stop doing it some day, so "with" is recommended) Commented Jun 22, 2013 at 11:16
  • Can we replace some characters in it? Commented Feb 2, 2022 at 15:26