0

I am using this code to get last xlsx file from ftp.

import pandas as pd
import ftplib


ftp = ftplib.FTP('ftpname.com', 'client','mdp')
ftp.retrlines('LIST')
ftp.cwd("/DATA")

names = ftp.nlst()

latest_time = None
latest_name = None

for name in names:
    time = ftp.sendcmd("MDTM " + name)
    if (latest_time is None) or (time > latest_time):
        latest_name = name
        latest_time = time

print(latest_name)

for the moment I can only get the file name as string, but I couldn't read it as a dataframe or to upload the xlsx file from the server to the local machine.

wysouf
  • 73
  • 6
  • 1
    See [Python FTP get the most recent file by date](https://stackoverflow.com/q/8990598/850848) – particularly the *"Downloading found file"* section at the end. – Though you might also want revisiting your code for finding the latest file, which is quite inefficient. – Martin Prikryl Oct 01 '21 at 10:53

1 Answers1

2

I don't think this question has anything to do with python specifically: you just need to fetch the file the same way you would fetch it with any other FTP client:

for name in names:
    time = ftp.sendcmd("MDTM " + name)
    if (latest_time is None) or (time > latest_time):
        latest_name = name
        latest_time = time

with open("myfile.xlsx", "wb") as f:
    ftp.retrbinary(f"RETR {latest_name}", f.write)

As to reading the resulting file in to a pandas DF, that's a separate question, but now that you have the file you can do it as you normally would.

wysouf
  • 73
  • 6
2e0byo
  • 5,305
  • 1
  • 6
  • 26