Найти - Пользователи
Полная версия: Чтение из файла N значений
Начало » Python для новичков » Чтение из файла N значений
1
Relrin
Предположим есть такой текстовый файл вида:
1 2 0,1 3 0,2 4 0,15
2 4 0,24 5 0,3
3 4 0,16 6 0,03
4 5 0,48 6 0,5
5 7 0,84
6 7 0,62

Как осуществить чтение из файла построчно, причем я должен хранить первую цифру, и потом забирать из строки по 2 элемента (цифра+дробное число), причем число такой последовательности в файле может быть большое и состоять из N элементов?
Soteric
with open(filename) as f:
for line in iter(f):
values = line.split(" ")
id = values[0]
integer = values[1]
fractional = values[2]
odnochlen
Soteric

with open(filename) as f:
    for line in f:
        values = line.split(" ")
        id, integer, fractional = values
py.user.next
odnochlen
id, integer, fractional = values
перекрываешь id(), и будет ошибка распаковки
>>> a, b = 'a b c'.split()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
>>>

>>> 'a b c d'.split(None, 2)
['a', 'b', 'c d']
>>> a, b = 'a b c d'.split(None, 2)[:2]
>>> a, b
('a', 'b')
>>>
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB