will using list comprehension to read a file automagically call close()

前端 未结 5 1721
独厮守ぢ
独厮守ぢ 2020-11-28 14:32

Does the following syntax close the file:

lines = [line.strip() for line in open(\'/somefile/somewhere\')]

Bonus points if you can demonstr

5条回答
  •  离开以前
    2020-11-28 14:51

    Yes because the "open" does not bound the file handle to any object, it will be closed as soon as the list comprehension is complete as it goes out of scope:

    #!/usr/bin/env python3
    import psutil
    
    print('before anything, open files: ', end='')
    print(psutil.Process().open_files())
    f = open('/etc/resolv.conf')
    print('after opening resolv.conf, open files: ', end='')
    print(psutil.Process().open_files())
    f.close()
    print('after closing resolv.conf, open files: ', end='')
    print(psutil.Process().open_files())
    print('reading /etc/services via a list comprehension')
    services = [ line.strip() for line in open('/etc/services') ]
    print('number of items in services: ', end='')
    print(len(services))
    print('after reading /etc/services through list comp, open files: ', end='')
    print(psutil.Process().open_files())
    

提交回复
热议问题