Table of Contents
ftp recursive download
pip install ftputil
大略搜尋了一下 python ftp 相關的模組 找不到 提供 recursive 下載檔案的功能
因此透過 ftputil 模組提共的 API 寫了一個 walk 函式 提供 recurisve 的方法列出檔案路徑
範例: 下載 所有檔名以 .stdf 結尾的檔案
import ftputil import os def walk(host, top, topdown=True): dirs, nodirs = [], [] names = host.listdir(top) for name in names: if host.path.isdir(os.path.join(top, name)): dirs.append(name) else: nodirs.append(name) if topdown: yield top, dirs, nodirs for name in dirs: new_path = os.path.join(top, name) for x in walk(host, new_path, topdown): yield x if not topdown: yield top, dirs, nodirs import glob try: ignore_file_list= open(max(glob.glob('_*.org'))).read().splitlines() except ValueError: ignore_file_list = [] with ftputil.FTPHost('IP', 'account', 'password') as host: download_list = [] for top, _, filenames in walk(host, '/SharkLJ1_CP'): for f in filenames: d = os.path.join(top, f) dirname = os.path.dirname(d) if not os.path.exists('.'+ dirname): os.makedirs('.' + dirname) if '.stdf' in d: if d in ignore_file_list: print('[ignore]', d) else: host.download(d, '.'+ d) download_list.append(d) print('[download]', d) import datetime filename1 = datetime.datetime.now().strftime("__%Y%m%d-%H%M-%S.org") download_record = open(filename1, 'w') for line in (download_list+ignore_file_list): download_record.write('%s'%line + '\n') download_record.close() if download_list: print('New') for item in download_list: print('[New]', item)