Python FTP: List Files in Directory and Download

Aug 28, 2020
import osfrom ftplib import FTPIP_OR_DOMAIN = ...USERNAME = ...PASSWORD = ...main_dir = 'data/videos'ftp = FTP(IP_OR_DOMAIN)# use ftp.login() for anonymous loginftp.login(USERNAME, PASSWORD)# ftp.cwd(main_dir)# ftp.retrlines('LIST')files = ftp.mlsd(main_dir)for filename, extra in files:    remote_path = os.path.join(main_dir, filename)    local_path = os.path.join('/content/video', dir, filename)    if os.path.isfile(local_path):      print(f"Exist: {local_path}")      continue    print(f"Download to: {local_path}")    os.makedirs(os.path.dirname(local_path), exist_ok=True)    with open(local_path, 'wb') as file :        ftp.retrbinary(f"RETR {remote_path}", file.write)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.