0

I have the following piece of code:

for line in open(fileName, 'r'):
    <do something>

Initially, I would assume that there is no need to close a file opened as read only, however after I have read through the answers to this question, it seems that I do have to close it, since Jython don't use reference counting and therefore won't close the file at the end of the loop.

How do I do that in this case, when I didn't define a file handler which I can close? Is such approach(as above) to open and read files is wrong?

Community
  • 1
  • 1
Eugene S
  • 6,709
  • 8
  • 57
  • 91

1 Answers1

1

It is safest and most portable to clean up after yourself. Just save the filehandle and close it after you are done with it.

Too bad there's no with in Jython at the moment. That would be the perfect solution here.

# wouldn't it be nice if we could just...
with open(fileName, 'r') as fh:
    for line in fh:
        # do something ...
janos
  • 120,954
  • 29
  • 226
  • 236