使用Python和ftplib在FTP服务器上发送图片时出现属性错误

使用Python和ftplib在FTP服务器上发送图片时出现属性错误,python,ftp,attributeerror,ftplib,Python,Ftp,Attributeerror,Ftplib,实际上,我正在尝试使用python脚本和ftplib将保存在计算机目录中的图片(.jpg)发送到FTP服务器。 图像所在的路径是:“D:/directory\u image”。 我使用Python2.7和ftplib中的.storbinary命令发送.jpg。 尽管我进行了搜索,但仍收到一条无法解决的错误消息: `AttributeError: 'str' object has no attribute 'storbinary' 以下是我的代码中导致问题的部分: from ftplib imp

实际上,我正在尝试使用python脚本和ftplib将保存在计算机目录中的图片(.jpg)发送到FTP服务器。 图像所在的路径是:“D:/directory\u image”。 我使用Python2.7和ftplib中的.storbinary命令发送.jpg。 尽管我进行了搜索,但仍收到一条无法解决的错误消息:

`AttributeError: 'str' object has no attribute 'storbinary'
以下是我的代码中导致问题的部分:

from ftplib import FTP
import time
import os

ftp = FTP('Host')
connect= ftp.login('user', 'passwd')
path = "D:/directory_image"
FichList = os.listdir( path )
i = len(FichList)
u = 0

While u < i :
    image_name= FichList[u]
    jpg_to_send = path + '/' + image_name
    file_open = open (image_name, 'rb')
    connect.storbinary('STOR '+ jpg_to_send, file_open)
    file_open.close()
    u = u + 1
从ftplib导入FTP
导入时间
导入操作系统
ftp=ftp(“主机”)
connect=ftp.login('user','passwd')
path=“D:/directory\u image”
FichList=os.listdir(路径)
i=len(FichList)
u=0
而u
我知道Storbinary()中的file参数必须是打开的file对象,而不是字符串。。。但在我的脚本中它是一个打开的文件对象,不是吗

非常感谢

克拉拉

试试:

from ftplib import FTP
import time
import os

session = FTP('Host', 'user', 'passwd')
path = "D:/directory_image"
FichList = os.listdir( path )


for image_name in FichList:                         #Iterate Each File
    jpg_to_send = os.path.join(path, image_name)    #Form full path to image file
    file_open = open(jpg_to_send, 'rb')
    session.storbinary('STOR '+ image_name, file_open)
    file_open.close()
在这里:

ftp.login()
返回带有登录结果的字符串(即“230登录成功”)

因此,这里:

connect.storbinary('STOR '+ jpg_to_send, file_open)
您正试图对字符串调用
storbinary
。。。解决方法很简单:

ftp.storbinary('STOR '+ jpg_to_send, file_open)
请注意:无论发生什么情况,您都希望确保文件已关闭,因此请替换以下内容:

file_open = open (image_name, 'rb')
ftp.storbinary('STOR '+ jpg_to_send, file_open)
file_open.close()
与:

无论发生什么情况,当退出带有
块的
时,文件将自动关闭

file_open = open (image_name, 'rb')
ftp.storbinary('STOR '+ jpg_to_send, file_open)
file_open.close()
with open(image_name, 'rb') as file_open:
    ftp.storbinary('STOR '+ jpg_to_send, file_open)