我想使用 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/