views:

29

answers:

3

When using a long running script which writes to an open text files, say for logging, which is the better approach: open a file, write to it as needed, and then close when done? Or open the file, write to it, and immediately close it every time? I can see advantages and disadvantages to both. Any thoughts or experiences?

A: 

Generally open and close is what I do unless there's a LOT of file access. Keep in mind that for VERY active and long running scripts you may have to deal with running out of file descriptors in your OS.

http://en.wikipedia.org/wiki/File%5Fdescriptor

Paul McMillan
A: 

I'm of the opinion that you only hold resources as long as you need them if there is a possibility of contention for the resource. For a long-running process I'd suggest that you open/seek/write/close only when you need to write to the file. This leaves the file available for other processes to use. Particularly with log files I'd like to be able to read them or rotate them periodically. If the process keeps the file open, it gets hard to do this. I think it's probably worth any extra code you need to write to enable multiple processes to use the resource.

tvanfosson
A: 

If you have a single log file that you're writing to, most of the time you'd keep it open for the duration of the script/program. If you write to many, many different files, then there would be a point where you'd have to close some of them because there are generally limits on the number of open file handles you can have at a single time. I can't imagine that you'd hit this limit except in very extreme cases, though.

bobbymcr