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

时间:2020-10-27 16:44:46

标签: python ftplib

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

以下是我尝试过的内容:

import ftplib
from pathlib import Path


def send_file(file_path, host, username, passwd):
    with ftplib.FTP(host, username, 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, "192.168.1.534", "user", "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

1 个答案:

答案 0 :(得分:3)

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

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