Does the following syntax close the file:
lines = [line.strip() for line in open(\'/somefile/somewhere\')]
Bonus points if you can demonstr
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())