Python FTP: List Files in Directory and Download

August 28, 2020
import os
from ftplib import FTP

IP_OR_DOMAIN = ...
USERNAME = ...
PASSWORD = ...
main_dir = 'data/videos'

ftp = FTP(IP_OR_DOMAIN)
# use ftp.login() for anonymous login
ftp.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)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.