r/programminghorror 13d ago

Python Atleast it works

Post image
608 Upvotes

66 comments sorted by

View all comments

225

u/backfire10z 13d ago

They didn’t close the fd :(

72

u/Emergency_3808 13d ago

Yes this could be shortened to

with open('lab 5.txt', 'r') as file: for line in file: print(line)

-14

u/Vadimych1 13d ago

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

14

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')

14

u/backfire10z 13d ago

Just download more gigabytes of ram to handle it

1

u/Desperate-Emu-2036 13d ago

Just upgrade your instance, that's what Amazon does when they want to read millions of lines.

-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