Message149393
| Author |
smarnach |
| Recipients |
Julian, eric.snow, giampaolo.rodola, ncoghlan, nikratio, rhettinger, smarnach |
| Date |
2011年12月13日.15:41:47 |
| SpamBayes Score |
5.275229e-05 |
| Marked as misclassified |
No |
| Message-id |
<1323790908.16.0.612869623142.issue13585@psf.upfronthosting.co.za> |
| In-reply-to |
| Content |
I think that the fact that Nick got the code to close multiple files wrong underlines that it is difficult to get right currently. Nick's code
try:
files = [open(fname) for fname in names]
# ...
finally:
for f in files:
f.close()
only closes the files if all of them were opened successfully. Moreover, `file.close()` can fail for various reasons, which would result in all remaining files being left open. When we fix both problems, the code becomes
try:
files = []
for fname in names:
files.append(open(fname))
# ...
finally:
for f in files:
try:
f.close()
except IOError:
pass
I think everyone will agree that the version using 'CleanupManager' is nicer. To be fair, we should note that the need to open many files simultaneously is not very common -- usually, we can make to with opening the files one by one. |
|