python下载FTP上面的文件夹
时间:2011-06-14
来源:互联网
FTP指定文件夹里的内容下载到本地,文件夹到底有多少层不知道
这个地方用递归我知道,但是写了几次都报错
希望哪位大侠贴下代码,十分感谢了
这个地方用递归我知道,但是写了几次都报错
希望哪位大侠贴下代码,十分感谢了
作者: zp307300084 发布时间: 2011-06-14
本帖最后由 iamacnhero 于 2011-06-14 17:27 编辑
ftp_mirror.py
复制代码
ftp_mirror.py
- # -*- encoding: utf8 -*-
- import os
- import sys
- import ftplib
-
- class FTPSync(object):
- def __init__(self):
- self.conn = ftplib.FTP('10.22.14.23', 'user', 'pass')
- self.conn.cwd('/') # 远端FTP目录
- os.chdir('/data/') # 本地下载目录
-
- def get_dirs_files(self):
- u''' 得到当前目录和文件, 放入dir_res列表 '''
- dir_res = []
- self.conn.dir('.', dir_res.append)
- files = [f.split(None, 8)[-1] for f in dir_res if f.startswith('-')]
- dirs = [f.split(None, 8)[-1] for f in dir_res if f.startswith('d')]
- return (files, dirs)
-
- def walk(self, next_dir):
- print 'Walking to', next_dir
- self.conn.cwd(next_dir)
- try:
- os.mkdir(next_dir)
- except OSError:
- pass
- os.chdir(next_dir)
-
- ftp_curr_dir = self.conn.pwd()
- local_curr_dir = os.getcwd()
-
- files, dirs = self.get_dirs_files()
- print "FILES: ", files
- print "DIRS: ", dirs
- for f in files:
- print next_dir, ':', f
- outf = open(f, 'wb')
- try:
- self.conn.retrbinary('RETR %s' % f, outf.write)
- finally:
- outf.close()
- for d in dirs:
- os.chdir(local_curr_dir)
- self.conn.cwd(ftp_curr_dir)
- self.walk(d)
-
- def run(self):
- self.walk('.')
-
- def main():
- f = FTPSync()
- f.run()
-
- if __name__ == '__main__':
- main()
作者: iamacnhero 发布时间: 2011-06-14
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28