I've written this code with the aim of exiting the code once the last line is reached and I've tried using the commented code but it only prints every alternating line.
try:
a = sys.argv[1]
with open(a, 'r') as f:
print(f.readline().strip('\n'))
while True:
x = input()
if x == '':
print(f.readline().strip('\n'))
# if not f.readline():
# exit()
continue
if x == 'q':
exit()
except OSError:
print("Error: Cannot open specified file.")
exit()
except IndexError:
print('Usage: python3 less.py <filename>')
exit()
TL;DR
while True:
x = input()
if x == '':
line = f.readline()
print(line.strip('\n'))
if line == '':
exit()
continue
if x == 'q':
exit()
The readline()
method in Python will always read the next line, so when you call it multiple times, it will continually read another line. Since for every iteration of your while loop, you call the function twice, you are effectively ignoring the first line and checking the second line. By saving the output of f.readline()
to a variable, you are not calling the function more than once per turn, and therefore will not skip any lines. Check out here for more information on Python file operations.