是否可以使用 Paramiko 指定文件的编码?

Is it possible to specify the encoding of a file with Paramiko?

我正在尝试使用 pysftp/Paramiko 通过 SFTP 读取 CSV。我的代码如下所示:

input_conn = pysftp.Connection(hostname, username, password)
file = input_conn.open("Data.csv")
file_contents = list(csv.reader(file))

但是当我这样做时,出现以下错误:

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

我知道这意味着文件应该采用 UTF-8 编码,但实际上不是。奇怪的是,如果我下载文件然后使用我的代码打开文件,我可以将编码指定为“macroman”并且不会出现错误:

with open("Data.csv", "r", encoding="macroman") as csvfile:
    file_contents = list(csv.reader(csvfile))

Paramiko 文档说文件的编码在 SFTP 上没有意义,因为它将所有文件都视为字节——但是,如果我使用,我如何才能让 Python 的 CSV 模块识别编码Paramiko 打开文件?

如果文件不大,加载两次内存没有问题,可以下载并转换内存中的内容:

with io.BytesIO() as bio:
    input_conn.getfo("Data.csv", bio)
    bio.seek(0)

    with io.TextIOWrapper(bio, encoding='macroman') as f:
        file_contents = list(csv.reader(f))

部分基于Convert io.BytesIO to io.StringIO to parse HTML page