阅读:9550回复:1
Python2.7之下载FTP文件
废话不多直接上代码,Python2.7之FTP下载
# -*- encoding: utf8 -*- import os import sys import ftplib import datetime class FTPSync(object): def __init__(self): str_today = datetime.date.today() self.conn = ftplib.FTP('FTP地址', 'FTP用户名', 'FTP密码') self.conn.cwd('远端FTP目录') # 远端FTP目录 os.chdir('本地下载目录') # 本地下载目录 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(): origin = sys.stdout str_today = datetime.date.today() fi = open('log输出文件', 'w') sys.stdout = fi # =================================== print 'Start of program' print 'Being processed...' f = FTPSync() f.run() print 'End of program' # =================================== sys.stdout = origin fi.close() if __name__ == '__main__': main() |
|
沙发#
发布于:2018-07-18 21:47
谢辛苦分享
|
|