Lem L
Lem L

Reputation: 1

FTP download of the latest files of the day

I need to connect to the FTP server in Python and download all the files that appeared only today from five different folders. Deleting files is not required.

I have just started to learn Python. We managed to connect and download all the files. How to do this only for today so that I don't download for yesterday and so on?

import ftplib
import os

ftp = ftplib.FTP('ftpserver.com')
ftp.login('user_ftp','ftp_pass')
ftp.cwd('/test/123')
filenames = ftp.nlst()

for filename in filenames:
    host_file = os.path.join(
        'C:\\test\\', filename
    )

    try:
        with open(host_file, 'wb') as local_file:
            ftp.retrbinary('RETR ' + filename, local_file.write)
    except ftplib.error_perm:
        pass

ftp.quit()

Upvotes: 0

Views: 50

Answers (1)

Lem L
Lem L

Reputation: 1

import ftplib
import os
from datetime import datetime

# Параметры FTP сервера
ftp_host = 'ftp_server'
ftp_user = 'ftp_user'
ftp_password = 'ftp_pass'

# Целевая локальная папка для сохранения файлов
local_folder = 'C:\\test'

def download_files_from_ftp(ftp_folder):
    ftp = ftplib.FTP(ftp_host)
    ftp.login(ftp_user, ftp_password)
    ftp.cwd(ftp_folder)

    files = ftp.nlst()
    today = datetime.now().date()

    for file in files:
        file_time = datetime.strptime(ftp.sendcmd('MDTM ' + file)[4:], "%Y%m%d%H%M%S").date()
        if file_time == today:
            local_filename = os.path.join(local_folder, file)
            with open(local_filename, 'wb') as local_file:
                ftp.retrbinary('RETR ' + file, local_file.write)

    ftp.quit()

# Список папок для загрузки файлов
ftp_folders = ['folder1','folder2','folder3']

# Загрузка файлов из каждой папки
for folder in ftp_folders:
    download_files_from_ftp(folder)

Upvotes: 0

Related Questions