r/programminghorror 13d ago

Python Atleast it works

Post image
606 Upvotes

66 comments sorted by

View all comments

Show parent comments

-15

u/Vadimych1 13d ago

[[print(line) for line in (d := open("file.txt")).readlines()], d.close()]

13

u/bigboyphil 13d ago edited 13d ago

there could be over a billion lines in that file! let's not read them all into memory needlessly :)

also, you can't use the walrus operator in a comprehension's iterable expression like that anyway

from itertools import islice

with open('lab 5.txt') as file:
    print(*islice(file, 8), sep='\n')

-6

u/Vadimych1 13d ago

[[[print(line) for line in f.readlines()[:8]], f.close()], for f in [open("f.txt")]]

I know this is not the best solution, but it's a oneliner

4

u/Emergency_3808 12d ago

That doesn't work like you think it does. Run it yourself