QMan5
QMan5

Reputation: 779

Why doesn't this code skip the first line of the file?

fp = open("Fruits.csv", 'r')
exampleDictionary = {}
line = fp.readline()
while line is not '':
    # the line can have some trailing characters, like 'newline'
    line = line.rstrip()
    items, types, numberItems, color  = line.split(',')

    # split it into parts, to get the total price
    exampleDictionary[items] = types
    # add this part's price to the total price of the car
    # remember: everything we get from the split() is a string.
    #price_of_car += int(total_price_of_part)
    
    print(items, types, numberItems, color)
    # read in a new line
    line = fp.readline()
print(exampleDictionary)
fp.close()

This outputs something like this:

Items Type Number of items Color
Apples Fruit 3 Red
Oranges Fruit 5 Orange
Mangos Fruit 4 Yellow
Legos Toys 6 Red
{'Items': 'Type', 'Apples': 'Fruit', 'Oranges': 'Fruit', 'Mangos': 'Fruit', 'Legos': 'Toys'}

When I don't include line = fp.readline() before the while loop it skips the first column. I was wondering if someone could explain why this happening.

The file looks like this:

  Items Type  Number of items  Color
  Apples Fruit 3 Red
  Oranges Fruit 5 Orange
  Mangos Fruit 4 Yellow
  Legos Toys 6 Red'

Upvotes: 0

Views: 54

Answers (1)

tamahom
tamahom

Reputation: 162

I know, it's not the optimal solution but it works like this

fp = open("Fruits.csv", 'r')
exampleDictionary = {}
line = fp.readline()
while line is not '':
    #Read line at first to skip the first line
    line = fp.readline()
    #check if line is ''
    if(line == ''):
        break
    # the line can have some trailing characters, like 'newline'
    line = line.rstrip()
    items, types, numberItems, color = line.split(",")

    # split it into parts, to get the total price
    exampleDictionary[items] = types
    # add this part's price to the total price of the car
    # remember: everything we get from the split() is a string.
    # price_of_car += int(total_price_of_part)
    print(items, types, numberItems, color)
print(exampleDictionary)
fp.close()

Or you can read the line two times at first and conserve your code.

Upvotes: 2

Related Questions