Python實現Ftp上傳下載

ybw8 9年前發布 | 24K 次閱讀 Python Python開發

些情況下,我們會使用FTP服務器存儲文件,這時,在腳本中,我們就會涉及到FTP的上傳下載操作了。

首先看下FTP文件的上傳操作,整個過程大致可以拆分成登陸、打開本地文件、文件傳輸、退出幾步,看下代碼

    try:  
       f = FTP(server)  
       try:  
          f.login(user, pwd)  
          localFile = open(localPath, "rb")  
          f.storbinary("STOR %s" % srcFile, localFile)  
          localFile.close()  
          f.quit()  
          return True  
       except:  
          f.quit()  
          return False  
    except:  
       return False  

文件下載的過程與上傳過程基本一致,大體分為登陸、切換到ftp目錄,打開本地文件、傳輸文件、退出幾步
    ftp = FTP()  
    ftp.connect(server, '21')  
    ftp.login(user, pwd)  
    ftp.cwd(os.path.dirname(srcFile).lstrip("/")) #選擇操作目錄  
    file_handler = open(savePath,'wb') #以寫模式在本地打開文件  
    ftp.retrbinary('RETR %s' % os.path.basename(srcFile),file_handler.write)#接收服務器上文件并寫入本地文件  
    file_handler.close()  
    ftp.quit()  

這樣,FTP文件的上傳下載過程就完成了

為了使用起來方便,我們再進行一次封裝操作,代碼如下:

    def FtpUpload(localPath, ftpPath, user="", pwd=""):
""" | ##@函數目的:從ftp上傳文件 """
dirs = str(ftpPath).split("/")
if len(dirs) < 4:
return False
if str(dirs[2]).count(".") != 3:
return False
server = dirs[2]
srcFile = ""
for item in dirs[3:]:
srcFile += "/" + str(item)

    try:  
        f = FTP(server)  
        try:  
            f.login(user, pwd)  
            localFile = open(localPath, "rb")  
            f.storbinary("STOR %s" % srcFile, localFile)  
            localFile.close()  
            f.quit()  
            return True  
        except:  
            f.quit()  
            return False  
    except:  
        return False  

def FtpDownLoad(ftpFile, savePath, user="", pwd=""):  
    dirs = str(ftpFile).split("/")  
    if len(dirs) < 4:  
        return False  
    server = dirs[2]  
    srcFile = ""  
    for item in dirs[3:]:  
        srcFile += "/" + str(item)  
    try:  
        ftp = FTP()  
        ftp.connect(server, '21')  
        ftp.login(user, pwd)  
        ftp.cwd(os.path.dirname(srcFile).lstrip("/")) #選擇操作目錄  
        file_handler = open(savePath,'wb') #以寫模式在本地打開文件  
        ftp.retrbinary('RETR %s' % os.path.basename(srcFile),file_handler.write)#接收服務器上文件并寫入本地文件  
        file_handler.close()  
        ftp.quit()  
    except:  
        print traceback.format_exc()  </pre><br />
 本文由用戶 ybw8 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!