I'm trying to upload mp4 file via ftp using ftplib
in Python. But I got UnicodeDecodeError.
Below is what I tried:
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")
Error:
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
open(file_path)
opens the file in text mode, so it'll treat the binary .mp4
file as if it was UTF8-encoded text.
You should open it in binary mode instead: open(file_path, 'rb')
.