python实现文件上传下载

创建自己的ftp类 myftp.py

#!/usr/bin/python
#coding:utf-8
#author:zhj
#info:数据传输平台

import ftplib, socket, os, sys

class MyFtp(object):
    def __init__(self, host, port, name, passwd):
        self.host = host
        self.port = port        
        self.name = name
        self.passwd  = passwd

    def LoginFtp(self, errorfile): #errorfile,错误信息输出到制定文件
        try:
            self.ftps = ftplib.FTP()
            self.ftps.connect(self.host,self.port)
        except (socket.error, socket.gaierror):
            with open(errorfile, 'w') as f:
                print >>f,'ERROR:cannot reach %s %s' % (self.host,self.port) #python version 2.X ;python 3.x print ("xxxxx",f)
            sys.exit(0)
            
        try:
            self.ftps.login(self.name,self.passwd)
        except ftplib.error_perm:
            with open(errorfile, 'w') as f:
                print >>f,'ERROR: cannot login %s %s %s' % (self.host,self.port,self.name)
            self.ftps.quit()
            sys.exit(0)
        self.buffer = 2048 #设置缓存大小

    def UpFtp(self, localpath, remotepath, errorfile):
        self.LoginFtp(errorfile)
        try:
            self.ftps.cwd(remotepath)
        except ftplib.error_perm:
            with open(errorfile, 'w') as f:
                print >>f,'ERRORL cannot CD to "%s"' % remotepath
            self.ftps.quit()
            sys.exit(0)
        self.ftps.set_debuglevel(0)
        file_open = open(localpath, 'rb')#打开文件 可读即可
        try:
            self.ftps.storbinary('STOR %s' % os.path.basename(localpath), file_open, self.buffer)
        except ftplib.error_perm:
            with open(errorfile, 'w') as f:
                print >>f,'ERROR: cannot read file "%s"' % localpath
            file_open.close()
            self.ftps.quit()
            sys.exit(0)
        self.ftps.set_debuglevel(0)
        file_open.close()
        self.ftps.quit()
        with open(errorfile, 'w') as f:
            print >>f,"RIGHT"

    def DownFtp(self, localpath, remotepath):
        self.LoginFtp()
        try:
            self.ftps.cwd(remotepath)
        except ftplib.error_perm:
            with open(errorfile, 'w') as f:
                print >>f,'ERRORL cannot CD to "%s"' % remotepath
            self.ftps.quit()
            sys.exit(0)
        self.ftps.set_debuglevel(0)
        file_down = open(localpath,'wb')
        try:
            self.ftps.retrbinary('RETR %s' % os.path.basename(localpath),file_down.write,self.buffer)
        except ftplib.error_perm:
            with open(errorfile, 'w') as f:
                print >>f,'ERROR: cannot write file "%s"' % localpath
            file_down.close()
            self.ftps.quit()
            sys.exit(0)
        self.ftps.set_debuglevel(0)
        file_down.close()   
        self.ftps.quit()
        sys.exit(0)
        with open(errorfile, 'w') as f:
            print >>f,"RIGHT"


你可能感兴趣的:(python)