Parsing an excel document with a WHILE loop (Python)

Viewed 68

I´m self learning Python by reading Python programming fundamentals by Kent D. Lee. In one exercise I´m asked to parse an excel document using a while loop. I understand how to do it with a for but the while is suggested because the first row of the table is just the description of each row and hence I want to omit it. Here is my for code:

file = open("Nissan2.cvs", "r")

for line in file:
    lst = line.split(",")
    print(lst)

For it to give me the information I want, I deleted the first row directly from the document but that is not the correct way, also I´m not interested in importing a library since I haven´t been introduced to them. Thanks in advance!

4 Answers

If you want a while loop, you can use:

line = file.readline()

while line:
    lst = line.split(",")
    print(lst)
    line = file.readline()

file.close()

Dont forget to close the file handler with file.close()

Just for what it's worth, a for loop is a much better way to solve this problem. Here's how I would do it with a while loop though (I am opening the file using a context manager, which will close the file automatically when I'm done using it):

with open('Nissan2.csv', 'r') as file:
    next_line = True
    while next_line:
        next_line = file.readline()
        if next_line:
            print(next_line)

I'm not sure why he recommended while but an easy solution is to keep a line counter, for example:

file = open("Nissan2.cvs", "r")

for line_count, line in enumerate(file):
    if line_count == 0:
        # This is the column names
    else:
        lst = line.split(",")
        print(lst)

Yet Another Method

with open("Nissan2.cvs", "r") as file: # with is preferred with open
  # skip header row
  next(file)

  while True:
    try:
      # Get the next line
      line = next(file)
      lst = line.split(",")
      print(lst)
    except StopIteration:
      # Catch stop iteration error (i.e. End of file)
      break  
Related