之前,有篇文章介绍了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 Falseftp = 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()原文:http://blog.csdn.net/sogouauto/article/details/44568893