Изменяется ли HttpResponseObject после read (). Decode ('utf-8') в методе python openurl? - PullRequest
0 голосов
/ 13 июля 2020

Я сейчас изучаю python 3 и играл с openurl, когда заметил, что после read (). Decode ('utf-8') длина моего объекта HTTP-ответа стала равна нулю, и я не могу понять, почему он ведет себя вот так.

story = urlopen('http://sixty-north.com/c/t.txt')
print(story.read().decode('utf-8'))
story_words = []
for line in story:
    line_words = line.decode('utf-8').split()
    for word in line_words:
        story_words.append(word)
story.close()
print(story_words)

При выполнении команды печати в строке 2 длина HTTP-ответа в истории изменяется с 593 на 0, и пустой массив печатается на словах истории. Если я удалю команду печати, массив story_words будет заполнен.

Output with read().decode()
It was the best of times
it was the worst of times
it was the age of wisdom
it was the age of foolishness
it was the epoch of belief
it was the epoch of incredulity
it was the season of Light
it was the season of Darkness
it was the spring of hope
it was the winter of despair
we had everything before us
we had nothing before us
we were all going direct to Heaven
we were all going direct the other way
in short the period was so far like the present period that some of
its noisiest authorities insisted on its being received for good or for
evil in the superlative degree of comparison only
[]

Output without it - 

['It', 'was', 'the', 'best', 'of', 'times', 'it', 'was', 'the', 'worst', 'of', 'times', 'it', 'was', 'the', 'age', 'of', 'wisdom', 'it', 'was', 'the', 'age', 'of', 'foolishness', 'it', 'was', 'the', 'epoch', 'of', 'belief', 'it', 'was', 'the', 'epoch', 'of', 'incredulity', 'it', 'was', 'the', 'season', 'of', 'Light', 'it', 'was', 'the', 'season', 'of', 'Darkness', 'it', 'was', 'the', 'spring', 'of', 'hope', 'it', 'was', 'the', 'winter', 'of', 'despair', 'we', 'had', 'everything', 'before', 'us', 'we', 'had', 'nothing', 'before', 'us', 'we', 'were', 'all', 'going', 'direct', 'to', 'Heaven', 'we', 'were', 'all', 'going', 'direct', 'the', 'other', 'way', 'in', 'short', 'the', 'period', 'was', 'so', 'far', 'like', 'the', 'present', 'period', 'that', 'some', 'of', 'its', 'noisiest', 'authorities', 'insisted', 'on', 'its', 'being', 'received', 'for', 'good', 'or', 'for', 'evil', 'in', 'the', 'superlative', 'degree', 'of', 'comparison', 'only']


1 Ответ

0 голосов
/ 13 июля 2020

Вызов urlopen возвращает файловый буферный объект. С помощью read вы можете получить ответ до определенного количества байтов или получить весь ответ до EOF, если не передать параметр. После чтения буфер пуст. Это означает, что вам нужно сохранить возвращаемое значение в переменной перед печатью.

...