How can I find out which line of code is leaving a file open?
Are you depending on the garbage collector to close your files? I.E. the handle goes out of scope and even though you've "closed" the file, it won't go away until GC runs. If the object chain never goes out of scope, GC cannot collect it. Also, if GC does not get an opportunity to run, they won't be collected either.
I ran into the same issue with a long running process, and "solved" it by redesigning my system, such that all file access happened inside of a child object. That object got removed from the reference chain after it was done being used, or some error occurred. This allowed the GC to collect the handles.
I recently got an exception on my server about "Too many open files". I checked lsof, and sure enough, there are a bunch of PDF files that remain open (all in the same directory). This particular file is managed through a Django FileField. I've tried to track down any places in my project that explicitly open the file by name, and there's only one place I can find, and from what I can tell the file is being closed correctly there. There may be other places where the file is remaining open, but I have no idea how to find out what piece of code is actually keeping the file open. I've tried simply grepping for calls to open() and file(), but no luck.
Is there any way to systematically track down what line of code is responsible for leaving the file open? 
EDIT: I understand how to properly open/close a file. My question is whether or not there is a way to track down an existing line of code that leaves is leaving a file open.