0

I am downloading a file from an ftp location and able to do it successfully with below code-

import ftplib
server = ftplib.FTP()
server.connect('HOST', PORT)
server.login('USER_NAME','PASSWORD')
server.dir()
server.retrbinary("RETR " + 'xyz.csv' ,open('xyz.csv', 'wb').write)
server.quit()

Now I have a requirement- need to check if the above file is updated then I need to run another python script.

For this purpose I thought to use the last modified date but unable to see any method in ftplib library for this.

Has anyone faced the same issue? How it can be resolved? Please suggest how to do it?

Ratan Uday Kumar
  • 5,738
  • 6
  • 35
  • 54
AnalyticsPy
  • 245
  • 2
  • 14
  • Possible duplicate of [How to get FTP file's modify time using Python ftplib](https://stackoverflow.com/questions/29026709/how-to-get-ftp-files-modify-time-using-python-ftplib) – tripleee Jul 17 '18 at 12:42

1 Answers1

1

You can use the dir method to get the last modified timestamps from the file listing, and parse the 6th to 8th fields on your own. Note that the 8th field can be either a year or a time of the day, in which case the year is the current year. But then again you don't necessarily have to parse the date/time at all since all you need is to detect change.

>>> from ftplib import FTP
>>> ftp = FTP('ftp.redhat.com')
>>> ftp.login()
'230 Login successful.'
>>> ftp.dir()
lrwxrwxrwx    1 ftp      ftp             1 Dec 19  2009 pub -> .
drwxr-xr-x   45 ftp      ftp          4096 Jul 05 16:46 redhat
>>> l=[]
>>> ftp.dir(lambda x: l.append(x))
>>> l
['lrwxrwxrwx    1 ftp      ftp             1 Dec 19  2009 pub -> .', 'drwxr-xr-x   45 ftp      ftp          4096 Jul 05 16:46 redhat']
>>>
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Glad to be of help. Yup have to do it manually in this case. Also, can you mark this answer as accepted if you find it to be correct? – blhsing Jul 17 '18 at 06:40
  • Parsing output which is formatted for human consumption is an antipattern. Fundamentally, this is identical to [parsing `ls`](https://mywiki.wooledge.org/ParsingLs) – tripleee Jul 17 '18 at 12:43
  • @tripleee This is FTP we're talking about. We have no low-level access to the remote file server. Parsing the file listing is the best we can do given what FTP has to offer. – blhsing Jul 17 '18 at 12:50
  • See the nominated duplicate. Modern FTP *does* provide low-level commands for these things, though it's a lot more crude than more recent protocols. – tripleee Jul 17 '18 at 12:52
  • @tripleee Many popular FTP servers are actually not modern at all. The example I used above, `ftp.redhat.com`, for one, does not support low-level commands such as `MLST`. – blhsing Jul 17 '18 at 12:58