TypeError:需要类似字节的对象,而不是';str';Python3下载长文件

TypeError:需要类似字节的对象,而不是';str';Python3下载长文件,python,python-3.x,blob,Python,Python 3.x,Blob,我试图用Python3下载一个BLOB格式的文件,这个文件对于一个数据库来说非常“沉重”。有人可以帮助我编写代码: fout = open('D:\files.zip','wb') def readBLOB (): try: conn = mysql.connector.connect(host='(IP)',user='(user)', passwd='(password)', db='(Database)', port=PORT) cursor = co

我试图用Python3下载一个BLOB格式的文件,这个文件对于一个数据库来说非常“沉重”。有人可以帮助我编写代码:

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'
(写入二进制或字节),所以您不能向它写入字符串-只能写入
字节
(准确地说,“类似字节的对象”,如错误消息所示)

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

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

哪一行给出了错误?您可以包括完整的堆栈跟踪吗?@jordanm Traceback(最近一次调用):文件“update hermes.py”,第24行,在readBLOB()文件“update hermes.py”,第17行,在readBLOB fout.write(cursor.fetchone()[0])中。类型错误:需要类似字节的对象,而不是“str”