美文网首页
_csv.Error: iterator should retu

_csv.Error: iterator should retu

作者: 山竹山竹px | 来源:发表于2020-05-15 16:02 被阅读0次

    按照官方文件

    “csvfile如果是文件则must be opened with the ‘b’.”

    with open('test.csv','rb') as file:
        reader = csv.reader(file)
        for row in reader:
            print(row)
    
    报错

    _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

    返回的是字符串而不是字符

    分析

    open(),加 ’b‘ 表示读取的是二进制文件。这里的csv是文本文件

    解决方法
    with open('test.csv','r') as file:
        reader = csv.reader(file)
        for row in reader:
            print(row)
    
    又报错...what?

    UnicodeDecodeError: 'gbk' codec can't decode byte 0x89 in position 31: illegal multibyte sequence

    gbk解码不了

    分析

    官方文件

    This version of the csv module doesn’t support Unicode input. Also, there are currently some issues regarding ASCII NUL characters.

    Accordingly, all input should be UTF-8 or printable ASCII to be safe

    解决
    with open('test.csv','r',encoding='utf-8') as file:
        reader = csv.reader(file)
        for row in reader:
            print(row)
           
    ['no.', 'name', 'grade', 'age']
    ['1', '小红', '三', '10']
    ['2', '米米', '二', '9']
    ['2', '阿敏', '二', '9']
    

    相关文章

      网友评论

          本文标题:_csv.Error: iterator should retu

          本文链接:https://www.haomeiwen.com/subject/xfgcohtx.html