使用shareplum和paramiko传递SharePoint文件对象失败,报AttributeError错误
解决paramiko putfo()传入bytes对象的报错问题
错误原因
你碰到的AttributeError: 'bytes' object has no attribute 'read',核心问题是paramiko.SFTPClient.putfo()要求第一个参数是带read()方法的类文件对象,但shareplum的get_file()返回的是原始字节(bytes)数据,这类数据没有文件对象的读写方法,所以触发了报错。
解决方法
用Python标准库的io.BytesIO把bytes数据包装成类文件对象,它会模拟文件的行为,提供read()方法,刚好适配putfo()的要求。
修改后的完整代码
import paramiko import io # 导入io模块 ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=host, port=port, username=username,password=password, look_for_keys=False) ftp = ssh_client.open_sftp() # 将bytes对象包装成BytesIO类文件对象 file_like_obj = io.BytesIO(file_obj) # 传入包装后的对象完成上传 ftp.putfo(file_like_obj, remotepath=file_name) # 手动关闭资源 file_like_obj.close() ftp.close() ssh_client.close()
更简洁的写法(自动管理资源)
可以用with语句自动处理资源关闭,不用手动调用close():
import paramiko import io ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=host, port=port, username=username,password=password, look_for_keys=False) with ssh_client.open_sftp() as ftp: with io.BytesIO(file_obj) as file_like_obj: ftp.putfo(file_like_obj, remotepath=file_name) ssh_client.close()
内容的提问来源于stack exchange,提问作者BlakeB9
相关产品推荐
相关产品推荐

