Первая строка CSV игнорируется, csv.reader() | Меню и списки. Доступ к различным строкам в CSV из простого меню input() и цикла

lol.txt выглядит следующим образом:

1,2,3\n
\n
4,5,6\n
\n
AwesomeSauce,12.3,10\n

Код, который я использую:

import csv

NumberAdult = input("Please enter the number of adults: ")
NumberAdult = int(NumberAdult)
NumberChild = input("Please enter the number of children: ")
NumberChild = int(NumberChild)
n = 0
with open ("lol.txt",'rt', newline = '\n') as f:
    csv_r = (line for line in csv.reader(f) if line)
    for row in csv_r:
        entries = [(name, float(price1), float(price2)) for name, price1, price2 in csv_r]
        for index, entry in enumerate(entries):
            price1 = float(entry[1])
            price2 = float(entry[2])
            print ("%i. %17s - %5.2f / %5.2f" % (index, entry[0], price1, price2))

choice = int(input("Which package would you like?: "))

packageChoice = (entries[choice])
for row in packageChoice:
    name = entry[0]
    AdultPrice = float(entry[1])
    ChildPrice = float(entry[2])

price = AdultPrice*NumberAdult + ChildPrice*NumberChild

print(name, price)

Вывод:

Пожалуйста, введите количество взрослых: 2
Пожалуйста, введите количество детей: 1
0. 4 - 5,00 / 6,00
1. AwesomeSauce — 12.30/10.00
Какой пакет вы бы хотели?: 1
AwesomeSauce 34.6

Это означает, что он игнорирует первую строку lol.txt — 1,2,3\n— потому что csv.reader(), по-видимому, обрабатывает эту строку как имена полей, а не данные.

Есть ли способ обойти это? Использовать csv.dictreader()или что-то еще для назначения имен полей независимо от самого файла?

Редактировать: Nevermind csv.reader(), он не рассматривает их как имена полей. Итак, похоже, проблема в этом разделе:

with open ("lol.txt",'rt', newline = '\n') as f:
    csv_r = (line for line in csv.reader(f) if line)
    for row in csv_r:

Теперь я не могу понять, что здесь делать - это самое близкое, что я заставил скрипт работать.Любые советы, условия поиска, что-нибудь?

Окончательное редактирование: Ничего, теперь все работает! У меня был цикл, о котором я забыл:

for row in csv_r:
   entries = [(name, float(price1), float(price2)) for name, price1, price2 in csv_r]

Из-за которого он пропускал первую строку. Спасибо dash из #python на freenode за то, что заставил меня снова взглянуть на эту строку!

Новая проблема:

import csv

NumberAdult = input("Please enter the number of adults: ")
NumberAdult = int(NumberAdult)
NumberChild = input("Please enter the number of children: ")
NumberChild = int(NumberChild)
n = 0
with open ("lol.txt",'rt', newline = '\n') as f:
    csv_r = (line for line in csv.reader(f) if line)
    entries = [(name, float(price1), float(price2)) for name, price1, price2 in csv_r]
    for index, entry in enumerate(entries):
        price1 = float(entry[1])
        price2 = float(entry[2])
        print ("%i. %17s - %5.2f / %5.2f" % (index, entry[0], price1, price2))

choice = int(input("Which package would you like?: "))

packageChoice = (entries[choice])
for row in packageChoice:
    name = entry[0]
    AdultPrice = float(entry[1])
    ChildPrice = float(entry[2])

price = AdultPrice*NumberAdult + ChildPrice*NumberChild

print(name, price)

Единственная «опция» (независимо от того, что вы вводите в качестве опции) — это 2., так как это последняя строка в списке записей.

>>>
Please enter the number of adults: 2
Please enter the number of children: 1
0.                 1 -  2.00 /  3.00
1.                 4 -  5.00 /  6.00
2.      AwesomeSauce - 12.30 / 10.00
Which package would you like?: 1
AwesomeSauce 34.6
>>>

Теперь я почти уверен, что проблема здесь:

csv_r = (line for line in csv.reader(f) if line)
entries = [(name, float(price1), float(price2)) for name, price1, price2 in csv_r]
for index, entry in enumerate(entries):

Или я должен сделать другой раздел, подобный этому, для результатов меню, я не уверен. Я собираюсь работать над реализацией обоих, чтобы попытаться устранить неполадки.

0
задан Jens Björnhager 16 December 2012 в 13:47
поделиться