如何将URL返回的多行内容追加到Python列表中
问题原因
你的代码存在两个核心逻辑错误:
- 你已经通过
for line in f遍历响应流的每一行,但循环内部又调用了f.read(),这个操作会一次性读完流内剩余的所有内容,读完后流就为空,下一轮循环没有内容可以遍历,因此仅执行一次就停止 - 拆分换行时使用了硬换行,正确的换行转义字符是
\n,两种读取逻辑混写也导致功能异常
修复方案
方案1:直接逐行读取(推荐)
无需额外读取全量内容,遍历过程中直接解码每行加入列表即可:
import urllib.request listOfStrings = [] try: with urllib.request.urlopen('https://www.cs.queensu.ca/home/cords2/bingo.txt') as f: for line in f: # 可按需添加strip()去除首尾换行、空白符 line_content = line.decode('utf-8').strip() listOfStrings.append(line_content) except urllib.error.URLError as e: print(e.reason) print(listOfStrings)
方案2:一次性读取全量内容再拆分
如果需要先拿到完整内容再处理,不需要额外写遍历循环:
import urllib.request listOfStrings = [] try: with urllib.request.urlopen('https://www.cs.queensu.ca/home/cords2/bingo.txt') as f: d = f.read().decode('utf-8') listOfStrings = d.split("\n") # 可选操作:过滤空行、去除每行首尾空白 listOfStrings = [i.strip() for i in listOfStrings if i.strip()] except urllib.error.URLError as e: print(e.reason) print(listOfStrings)
内容的提问来源于stack exchange,提问作者codore
相关产品推荐
相关产品推荐

