python - 在Python中从文件中读取数字,忽略b'

标签 python python-3.x

我想使用 Python 从 url 读取数字列表,例如:

1,2,3,4,5,6
2,3,2,3,2,3
etc

我尝试过:

list.append([int(n) for n in line.strip().split(',')])

但是我使用的是 Python 3.2,这会出现错误:“TypeError: Type str does not support the buffer API”,因为 Python 3 将输入读取为字节。

所以我尝试将行转换为字符串:

list.append([int(n) for n in str(line).strip().split(',')])

但现在我在每行的开头都有 b' 并出现错误:ValueError: invalidliteral for int() with base 10: "b'1"

是否有一种优雅的方法来获取这些数字,或者我是否需要捕获字符串,去掉前两个字符,然后转换为 int?

最佳答案

您需要将字节解码为文本:

line = line.decode('ascii')

然后分割该行并转换为整数:

list.append([int(n) for n in line.split(',')])

int() 可以处理额外的空白,因此实际上不需要剥离。

关于python - 在Python中从文件中读取数字,忽略b',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30333549/

相关文章:

python - Kivy Label 验证 IP 地址时无法刷新

python-3.x - MIMEImage 未显示在电子邮件正文中/尝试在电子邮件中嵌入图像

python - 无法在 Windows 10 中下载 Django 2.0.7

python - 如何在Python中求矩阵指数的积分

python - 如何获取分隔符出现的合并计数

Python 连接拒绝错误 : [Errno 61] Connection refused

python - Django 装饰器根据用户类型进行重定向

python - SQLAlchemy:如何将数据从旧数据库中的一个表传输到新/不同数据库中的另一个表?

python - .在没有按我预期的方式运行之后

sql-server - 升级到 Python 3.6 和 SQL Server 2016 后出现 Pymssql 错误 20017