0

I'm trying to write a python script to download files from the FTP server, the below code works for me, but I'm curious is there any way to download the files with the original modify time from FTP. Is that is possible with python?

Example: FileZilla have a feature to download the files with the original date time

with open(fileName,'wb') as write
    def writeData(chunk):
        fwrite.write(chunk)
    ftp_client.retrbinary('RETR {}'.format(downFileName), writeData)
Jason
  • 65
  • 7
  • 2
    https://stackoverflow.com/questions/11348953/how-can-i-set-the-last-modified-time-of-a-file-from-python –  Mar 27 '21 at 11:26
  • 1
    FileZilla justs sets the timestamp afterwards. See link above to see how you can do the same. –  Mar 27 '21 at 11:27
  • 1
    See [how to get the modified time from FTP server](https://stackoverflow.com/questions/29026709/how-to-get-ftp-files-modify-time-using-python-ftplib) –  Mar 27 '21 at 11:30

1 Answers1

0

As @Justin correctly commented, just set the timestamp after the download.

remote_path = "/remote/path/foo.txt"
local_path = "/local/path/foo.txt"
timestamp = ftp.voidcmd("MDTM " + remote_path)[4:].strip()
mtime = parser.parse(timestamp)

with open(local_path, "wb") as f:
    ftp.retrbinary("RETR " + remote_path, f.write)

os.utime(local_path, (mtime.timestamp(), mtime.timestamp()))

Some references:


Though were you downloading all files in a folder, i would be an overkill to call MDTM for each. It that case, you can retrieve the timestamp from the directory listing retrieved using mlsd or `dir. See How to get FTP file's modify time using Python ftplib.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992