【问题标题】:Reading numbers from file in Python, ignoring b'在 Python 中从文件中读取数字,忽略 b'
【发布时间】:2015-05-20 02:39:32
【问题描述】:

我想使用 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 doesn't support the buffer API”,因为 Python 3 将输入读取为字节。

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

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

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

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

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

    line = line.decode('ascii')
    

    然后分行,转成整数:

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

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

    【讨论】:

    • 这就是我想要的。谢谢(我会尽可能接受你的回答)
    猜你喜欢
    • 2012-10-29
    • 2017-07-26
    • 2016-08-12
    • 2014-02-23
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多