之前,有篇文章介紹了http文件的下載,有些情況下,我們會使用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()