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"


發佈了18 篇原創文章 · 獲贊 19 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章