1. 连接FTP server
import ftplib
ftp = ftplib.FTP(ftpserver, user, passwd)
等同于
import ftplib
ftp = ftplib.FTP()
ftp.connect(ftpserver)
ftp.login(user,passwd)
对于初始化函数FTP(),如果指定host,则自动调用connect函数,如果指定了user和passwd,则自动调用login,如果都没指定,就什么都不做,需要显示调用。
2. upload
import ftplib def uploadToFTP(filename, targetdir, ftpserver, user="user", passwd=""):
rtd = 0
targetdir = targetdir.split(ftpserver)[-1] # remove ftpserver string from targetdir string if contain
fp = open(filename, 'rb')
ftp = ftplib.FTP(ftpserver, user, passwd) # make connection and login FTP
try:
ftp.cwd(targetdir)
except ftplib.error_perm:
print "Error: cannot upload to FTP, no such folder"
return -2
try:
ftp.storbinary('STOR %s/%s'%(targetdir,filename), fp)
except Exception, e:
traceback.print_exc()
rtd = 1
finally:
fp.close()
ftp.quit()
return rtd
3. 下载
# ftp.retrbinary(cmd, callback, blocksize=8192, rest=None) def downloadfile()
remotepath = "/home/pub/dog.jpg";
localpath = 'f:\\test\\dog.jpg'
fp = open(localpath,'wb') #以写模式在本地打开文件 ftp.retrbinary('RETR ' + remotepath,fp.write,bufsize) #接收服务器上文件并写入本地文件 ftp.set_debuglevel(0) #关闭调试
fp.close()
ftp.quit() #退出ftp服务器
官方文档:
https://docs.python.org/3/library/ftplib.html#ftplib.FTP.transfercmd