您的示例不起作用,因为该read
语句返回的数据是“字节对象”。您需要使用适当的编码对其进行解码。另请参阅文档request.urlopen
,file.read
以及字节数组操作。
下面给出了一个完整的工作示例:
#!/usr/bin/env python3
import urllib.request
# Example URL
url="http://ntl.matrix.com.br/pfilho/oldies_list/top/lyrics/black_or_white.txt"
# Open URL: returns file-like object
lyrics=urllib.request.urlopen(url)
# Read raw data, this will return a "bytes object"
text=lyrics.read()
# Print raw data
print(text)
# Print decoded data:
print(text.decode('utf-8'))