【问题标题】:About encode/decode in ftplib in python3关于python3中ftplib中的编码/解码
【发布时间】:2012-10-27 02:26:44
【问题描述】:

我有一个处理 ftp 服务器上的文件名列表的请求。但文件名包含亚洲字符和其他未知字符。所以我需要判断哪个文件名可以用gb2312解码,哪个可以用iso-8859-1解码。这意味着如果使用 gb2312 无法获取文件名列表,则使用 iso-88591-1 获取。所以我不知道如何在ftplib中的以下函数中编写代码

def retrlines(self, cmd, callback = None):
    """Retrieve data in line mode.  A new port is created for you.

    Args:
      cmd: A RETR, LIST, NLST, or MLSD command.
      callback: An optional single parameter callable that is called
                for each line with the trailing CRLF stripped.
                [default: print_line()]

    Returns:
      The response code.
    """
    if callback is None: callback = print_line
    resp = self.sendcmd('TYPE A')
##################I need to update here############################
    with self.transfercmd(cmd) as conn, \
             conn.makefile('r', encoding='iso-8859-1') as fp:
###################################################################
        while 1:

            line = fp.readline()
            print(line)

            if self.debugging > 2: print('*retr*', repr(line))
            if not line:
                break
            if line[-2:] == CRLF:
                line = line[:-2]
            elif line[-1:] == '\n':
                line = line[:-1]
            callback(line)
    return self.voidresp()

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您没有包含太多代码,因此很难准确判断发生了什么。但作为一般规则,如果您正在与之交互的数据在其编码使用方面不一致,您将不得不以二进制模式与之交互。

    所以尽量不要传入编码。希望这会给您返回字节数据,然后您可以根据每个文件的需要进行编码/解码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-11
      • 2016-10-04
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多