f.readline()
on a file open in text mode returns the empty string when it reaches the end of the file; the black screen is the infinite series of print
s that produce a newline and nothing else.
You don't want a while
loop for this case generally; the Pythonic solution is:
def get_line(filepath):
with open(filepath, "r") as f: # Use with to manage, so manual close not needed
for line in f: # Files are iterables of their lines
print(line) # Change to print(line, end='') to avoid added blank lines
# or use sys.stdout.write(line)
Or if you must use a while
:
def get_line(filepath):
with open(filepath, "r") as f:
# Loop ends when line ends up empty
# Relies on 3.8+'s assignment expression, aka walrus operator
while line := f.readline():
print(line)
The pre-walrus version of the while
loop approach would be:
while True:
line = f.readline()
if not line:
break
print(line)
But in practice, the for
loop approach is almost always what you want.