Python 尝试上传 mp4 文件时出现 ftplib UnicodeDecodeError
Python ftplib UnicodeDecodeError while trying to upload mp4 file
我正在尝试使用 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
open(file_path)
opens the file in text mode,因此它将二进制 .mp4
文件视为 UTF8 编码文本。
您应该改为以二进制模式打开它:open(file_path, 'rb')
。
我正在尝试使用 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
open(file_path)
opens the file in text mode,因此它将二进制 .mp4
文件视为 UTF8 编码文本。
您应该改为以二进制模式打开它:open(file_path, 'rb')
。