Automating file uploads and cleanup with Python and FTP
Keeping an FTP drop folder clean is tedious by hand. When a process depends on sending recurring log files, a script that uploads, archives, and cleans up on its own saves a lot of babysitting.
This script connects to a remote folder, uploads every CSV in a local folder, moves each sent file into a local archive, then deletes anything older than seven days from both the archive and the remote folder. It only uses Python's standard library.
import time
from ftplib import FTP_TLS
from pathlib import Path
FTP_HOST = "ftp.example.com"
FTP_USER = "upload_user"
FTP_PASS = "change-me" # load from an environment variable in real use
REMOTE_DIR = "/remote/logs"
LOCAL_DIR = Path(r"C:\DataLogs")
ARCHIVE_DIR = LOCAL_DIR / "Uploaded"
MAX_AGE_DAYS = 7
cutoff = time.time() - MAX_AGE_DAYS * 86400
ARCHIVE_DIR.mkdir(exist_ok=True)
with FTP_TLS(FTP_HOST) as ftp:
ftp.login(FTP_USER, FTP_PASS)
ftp.prot_p() # encrypt the data channel too
ftp.cwd(REMOTE_DIR)
# Upload, then archive locally
for path in LOCAL_DIR.glob("*.csv"):
with path.open("rb") as f:
ftp.storbinary(f"STOR {path.name}", f)
path.replace(ARCHIVE_DIR / path.name)
print(f"Uploaded {path.name}")
# Remove old remote files (needs a server that supports MLSD)
for name, facts in ftp.mlsd(facts=["type", "modify"]):
if facts.get("type") != "file":
continue
modified = time.mktime(time.strptime(facts["modify"][:14], "%Y%m%d%H%M%S"))
if modified < cutoff:
ftp.delete(name)
print(f"Deleted remote {name}")
# Remove old local archive files
for path in ARCHIVE_DIR.glob("*.csv"):
if path.stat().st_mtime < cutoff:
path.unlink()
print(f"Deleted archived {path.name}")
Run it from Task Scheduler or cron. If your server only speaks plain FTP, swap FTP_TLS for FTP and drop the prot_p() call, but treat that as a reason to ask for FTPS or SFTP.