編寫Python腳本來(lái)實(shí)現(xiàn)最簡(jiǎn)單的FTP下載的教程
訪問(wèn)FTP,無(wú)非兩件事情:upload和download,最近在項(xiàng)目中需要從ftp下載大量文件,然后我就試著去實(shí)驗(yàn)自己的ftp操作類,如下(PS:此段有問(wèn)題,別復(fù)制使用,可以參考去試驗(yàn)自己的ftp類!)
import os
from ftplib import FTP
class FTPSync():
def __init__(self, host, usr, psw, log_file):
self.host = host
self.usr = usr
self.psw = psw
self.log_file = log_file
def __ConnectServer(self):
try:
self.ftp = FTP(self.host)
self.ftp.login(self.usr, self.psw)
self.ftp.set_pasv(False)
return True
except Exception:
return False
def __CloseServer(self):
try:
self.ftp.quit()
return True
except Exception:
return False
def __CheckSizeEqual(self, remoteFile, localFile):
try:
remoteFileSize = self.ftp.size(remoteFile)
localFileSize = os.path.getsize(localFile)
if localFileSize == remoteFileSize:
return True
else:
return False
except Exception:
return None
def __DownloadFile(self, remoteFile, localFile):
try:
self.ftp.cwd(os.path.dirname(remoteFile))
f = open(localFile, 'wb')
remoteFileName = 'RETR ' + os.path.basename(remoteFile)
self.ftp.retrbinary(remoteFileName, f.write)
if self.__CheckSizeEqual(remoteFile, localFile):
self.log_file.write('The File is downloaded successfully to %s' + '\n' % localFile)
return True
else:
self.log_file.write('The localFile %s size is not same with the remoteFile' + '\n' % localFile)
return False
except Exception:
return False
def __DownloadFolder(self, remoteFolder, localFolder):
try:
fileList = []
self.ftp.retrlines('NLST', fileList.append)
for remoteFile in fileList:
localFile = os.path.join(localFolder, remoteFile)
return self.__DownloadFile(remoteFile, localFile)
except Exception:
return False
def SyncFromFTP(self, remoteFolder, localFolder):
self.__DownloadFolder(remoteFolder, localFolder)
self.log_file.close()
self.__CloseServer()
相關(guān)文章
python 使用matplotlib 實(shí)現(xiàn)從文件中讀取x,y坐標(biāo)的可視化方法
今天小編就為大家分享一篇python 使用matplotlib 實(shí)現(xiàn)從文件中讀取x,y坐標(biāo)的可視化方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
Python strip lstrip rstrip使用方法
Python中的strip用于去除字符串的首位字符,同理,lstrip用于去除左邊的字符,rstrip用于去除右邊的字符。這三個(gè)函數(shù)都可傳入一個(gè)參數(shù),指定要去除的首尾字符。2008-09-09
使用beaker讓Facebook的Bottle框架支持session功能
這篇文章主要介紹了使用beaker讓Facebook的Bottle框架支持session功能,session在Python的Django等框架中內(nèi)置但在Bottle中并沒(méi)有被集成,需要的朋友可以參考下2015-04-04
CentOS 7下安裝Python3.6 及遇到的問(wèn)題小結(jié)
這篇文章主要介紹了CentOS 7下安裝Python3.6 及遇到的問(wèn)題小結(jié),需要的朋友可以參考下2018-11-11
Python實(shí)現(xiàn)博客快速備份的腳本分享
本文針對(duì)博客園實(shí)現(xiàn)了一個(gè)自動(dòng)備份腳本,可以快速將自己的文章備份成Markdown格式的獨(dú)立文件,備份后的md文件可以直接放入到hexo博客中,感興趣的可以了解一下2022-09-09

