TypeError: a bytes-like object is required, not 'str' Python 3 download long file

TypeError: a bytes-like object is required, not 'str' Python 3 download long file

我正在尝试下载 Python 3 的 BLOB 格式的文件,此文件非常 'heavy' 用于数据库。有人可以帮助我处理我的代码:

fout = open('D:\files.zip','wb')
def readBLOB ():
   try:
        conn = mysql.connector.connect(host='(IP)',user='(user)', passwd='(password)', db='(Database)', port=PORT)
        cursor = conn.cursor()
        sql_fetch_blob_query = "SELECT archivo FROM versiones_archivos order by id desc limit 1"
        cursor.execute (sql_fetch_blob_query)
        fout.write(cursor.fetchone()[0])
        fout.close()

    finally:
        if (conn.is_connected()):
            cursor.close()
            conn.close()
readBLOB()

我得到的错误如下

TypeError: a bytes-like object is required, not 'str'

python 中的任何专家都可以帮助我解决问题或对我的脚本有其他替代方案,我将不胜感激

显然,cursor.fetchone()[0] 是一个字符串,但您以 'wb' 打开文件(写入 Binary,或 Bytes),所以你不能向它写入字符串 - 只能写入 bytes(准确地说,"bytes-like objects",如错误消息所述)。

您应该对字符串进行编码以获取字节:

try:
   ...
   fout.write(cursor.fetchone()[0].encode())
finally:
   ...
   # don't forget to close the file even if there's an error
   fout.close()