微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试上传mp4文件时,Python ftplib UnicodeDecodeError

如何解决尝试上传mp4文件时,Python ftplib UnicodeDecodeError

我正在尝试在Python中使用ftplib通过ftp上传mp4文件。但是我收到了UnicodeDecodeError。

以下是我尝试过的内容

import ftplib
from pathlib import Path


def send_file(file_path,host,username,passwd):
    with ftplib.FTP(host,passwd) as session,open(file_path) as file:
        session.cwd("relevant/path")
        session.storbinary(f"STOR {file_path}",file)
        session.dir()


f = str(Path("SubVideoExtractortest_output.mp4"))
send_file(f,"192.168.1.534","user","pass")

错误

Traceback (most recent call last):
  File "test_ftp.py",line 17,in <module>
    send_file(f,"pass")
  File "test_ftp.py",line 12,in send_file
    session.storbinary(f"STOR {file_path}",file)
  File "/usr/lib/python3.8/ftplib.py",line 489,in storbinary
    buf = fp.read(blocksize)
  File "/usr/lib/python3.8/codecs.py",line 322,in decode
    (result,consumed) = self._buffer_decode(data,self.errors,final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb8 in position 42: invalid start byte

解决方法

open(file_path) opens the file in text mode,因此它将二进制.mp4文件视为UTF8编码的文本。

您应该改为以二进制模式打开它:open(file_path,'rb')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。