編寫Python腳本來實(shí)現(xiàn)最簡(jiǎn)單的FTP下載的教程
訪問FTP,無非兩件事情:upload和download,最近在項(xiàng)目中需要從ftp下載大量文件,然后我就試著去實(shí)驗(yàn)自己的ftp操作類,如下(PS:此段有問題,別復(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 sort、sorted高級(jí)排序技巧分享(key的使用)
這篇文章主要介紹了python sort、sorted高級(jí)排序技巧(key的使用),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
Python實(shí)現(xiàn)自動(dòng)化處理每月考勤缺卡數(shù)據(jù)
不管是上學(xué)還是上班都會(huì)統(tǒng)計(jì)考勤,有些學(xué)?;蚬緯?huì)對(duì)每月缺卡次數(shù)過多(比如三次以上)的人員進(jìn)行處罰。本文提供了Python自動(dòng)處理考勤和日志缺失的方法,需要的可以參考一下2022-06-06
Python 編碼處理-str與Unicode的區(qū)別
本文主要介紹Python 編碼處理的問題,這里整理了相關(guān)資料,并詳細(xì)說明如何處理編碼問題,有需要的小伙伴可以參考下2016-09-09
python測(cè)試攻略pytest.main()隱藏利器實(shí)例探究
在Pytest測(cè)試框架中,pytest.main()是一個(gè)重要的功能,用于啟動(dòng)測(cè)試執(zhí)行,它允許以不同方式運(yùn)行測(cè)試,傳遞參數(shù)和配置選項(xiàng),本文將深入探討pytest.main()的核心功能,提供豐富的示例代碼和更全面的內(nèi)容,2024-01-01
python 七種郵件內(nèi)容發(fā)送方法實(shí)例
這篇文章主要介紹了python 七種郵件內(nèi)容發(fā)送方法實(shí)例,需要的朋友可以參考下2014-04-04
python 默認(rèn)參數(shù)相關(guān)知識(shí)詳解
這篇文章主要介紹了python 默認(rèn)參數(shù)相關(guān)知識(shí)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
python使用cartopy在地圖中添加經(jīng)緯線的示例代碼
gridlines可以根據(jù)坐標(biāo)系,自動(dòng)繪制網(wǎng)格線,這對(duì)于普通繪圖來說顯然不必單獨(dú)拿出來說說,但在地圖中,經(jīng)緯線幾乎是必不可少的,本文將給大家介紹了python使用cartopy在地圖中添加經(jīng)緯線的方法,需要的朋友可以參考下2024-01-01

