0

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()
ter123
  • 21
  • 7

2 Answers2

1

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.

  • 1
    Thanks for the help! Just another question, how can I prevent the program from printing the last empty line? – ter123 Apr 20 '20 at 04:26
  • 1
    No problem, and you would just swap the order of the `print()` and the `if` statement. That is to say, make sure you check for the blank string *before* you print it out. – cpchristensen Apr 20 '20 at 04:29
  • 1
    Note that [`exit()`](https://docs.python.org/3/library/constants.html#exit) should not be used in programs. Use [`sys.exit()`](https://docs.python.org/3/library/sys.html#sys.exit) instead. See also [this](https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python) or [this](https://stackoverflow.com/questions/19747371/python-exit-commands-why-so-many-and-when-should-each-be-used) SO question. – wovano Sep 13 '21 at 13:59
1

Yup, cpchristensen is right. I'd like to add that I believe there's a StopIteration exception that would execute once it reaches EOF. So, you could do something like this to exit the script once the exception triggers:

with open(sys.argv[1]) as lines:
    try:
        while True:              
            cur_line = next(lines)
            # ... do something with current line
    except StopIteration:
        exit()
alexako
  • 122
  • 7