天天看点

Python 使用 Paramiko 操作文件时发生 UTF8 错误

Paramiko 默认情况下获取远程文件, 默认以 UTF-8 的编码读取文件内容, 出现以下报错:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 124: invalid start byte

           

出现以上情况时, 可以手动设置 Paramiko 读取文件时使用二进制模式, 并对获取到的内容进行 UTF-8 解码:

remote_file = sftp.open(remoteName, "rb")
for line in remote_file:
    print(line.decode("utf8", "ignore"))