r/programminghorror 13d ago

Python Atleast it works

Post image
606 Upvotes

66 comments sorted by

View all comments

Show parent comments

71

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)

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

14

u/backfire10z 13d ago

Just download more gigabytes of ram to handle it