Mar-15-2024, 03:24 PM
The goal of the script is to grab the last file on the ftp site and save it in a network folder. I am not familiar with debugging the code to see where issues are, and I pulled this code from another article but it seems like it should have been straight forward. Also wondering if my values are in the correct place also, if I am using this example do I enter my values for the ftp host, user, pw, etc. on just the first line "def...."? I inputted my values for the ftp credentials everywhere in the code it had those statements, which I don't think hurts but probably not efficient. When I ran the script, something fired off and the command black screen showed for a milisecond. All of this is really new to me and only had some success writing my own code that called a SQL DB and outputted files, this FTP stuff is racking my head.
from ftplib import FTP
import os
import datetime
def download_most_recent_file('ftp.example.com', 'your_username', 'your_password', '/remote/directory', '/local/directory'):
try:
# Connect to FTP server
ftp = FTP(ftp_host)
ftp.login(your_username, your_password)
# Change to the specified directory
ftp.cwd(/remote/directory)
# List files and get the most recent one
files = ftp.nlst()
files_with_dates = [(file, ftp.voidcmd(f'MDTM {file}')[4:]) for file in files]
most_recent_file = max(files_with_dates, key=lambda x: datetime.datetime.strptime(x[1], "%Y%m%d%H%M%S")[0])
# Download the most recent file
file_name = most_recent_file[0]
local_file_path = os.path.join(/local/directory, file_name)
with open(local_file_path, 'wb') as local_file:
ftp.retrbinary('RETR ' + file_name, local_file.write)
print(f"Downloaded most recent file: {file_name}")
except Exception as e:
print(f"Error: {e}")
finally:
ftp.quit()
# Example usage
ftp_host = 'ftp.example.com'
ftp_user = 'your_username'
ftp_password = 'your_password'
ftp_directory = '/remote/directory'
local_directory = '/local/directory'
download_most_recent_file(ftp_host, ftp_user, ftp_password, ftp_directory, local_directory)
