2 ms·
nah, way better to use a generator... with open("a.txt") as f: c = ["{0} : {1}".format(x,y) for x,y in enumerate(f,1) ] for x in c: pri
by nobodysfool 13y ago
nah, way better to use a generator...
with open("a.txt") as f:
c = ["{0} : {1}".format(x,y) for x,y in enumerate(f,1) ]
for x in c:
print x,
- prutschman 13y agoc is assigned a list, not a generator. Switching the square brackets for parenthesis creates a generator, but attempting to access the elements will fail because f was closed after exiting the 'with' scope. <ipython-input-8-e2c5ebe72b17> in <module>() ----> 1 for x in c: 2 print x, 3 <ipython-input-7-9460e3a04a4e> in <genexpr>(***failed resolving arguments***) 1 with open("/tmp/foo.txt") as f: ----> 2 c = ("{0} : {1}".format(x,y) for x,y in enumerate(f,1)) 3 ValueError: I/O operation on closed file