通过python下载FTP上的文件夹的实现代码
程序员文章站
2022-05-14 08:58:42
复制代码 代码如下:# -*- encoding: utf8 -*-import osimport sysimport ftplibclass ftpsync(object...
复制代码 代码如下:
# -*- encoding: utf8 -*-
import os
import sys
import ftplib
class ftpsync(object):
def __init__(self):
self.conn = ftplib.ftp('10.22.33.46', '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()