0

I use the following code to read a csv file

f = csv.reader(open(filename, 'rb'))

Then there's no way I can close filename, right? Is there any harm of doing so or is there a better way of reading it?

LWZ
  • 11,670
  • 22
  • 61
  • 79
  • 1
    Yes, there is some harm: your file can be kept open, so spending system resources and maybe locking this file from access. – sshilovsky Sep 15 '13 at 18:33

1 Answers1

4

There is, use context managers:

with open(filename, 'rb') as handle: 
    f = csv.reader(handle)

In general an open unused file descriptor is a resource leak and should be avoided.


Interestingly in the case of files, at least the file descriptor is released, as soon as there is no reference to the file any more (see also this answer):

#!/usr/bin/env python

import gc
import os
import subprocess

# GC thresholds (http://docs.python.org/3/library/gc.html#gc.set_threshold)
print "Garbage collection thresholds: {}".format(gc.get_threshold())

if __name__ == '__main__':

    pid = os.getpid()

    print('------- No file descriptor ...')    
    subprocess.call(['lsof -p %s' % pid], shell=True)

    x = open('/tmp/test', 'w')
    print('------- Reference to a file ...')
    subprocess.call(['lsof -p %s' % pid], shell=True)

    x = 2
    print('------- FD is freed automatically w/o GC')
    subprocess.call(['lsof -p %s' % pid], shell=True)
Community
  • 1
  • 1
miku
  • 181,842
  • 47
  • 306
  • 310