How to make a Python script to download a file from a FTP server

12,827

I edited my answer to be more simpler ..now we will need to use FtpLib

the code below is straightforward and it's elegant :D

import ftplib

path = 'pub/Health_Statistics/NCHS/nhanes/2001-2002/'
filename = 'L28POC_B.xpt'

ftp = ftplib.FTP("Server IP") 
ftp.login("UserName", "Password") 
ftp.cwd(path)
ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write)
ftp.quit()

Just in case you need some explanation:

path is obviously the location of the file in the ftp server

filename is the name + extension of the file you want to download form server

ftp.login is where you'll put your credentials(username, password)

ftp.cwd will change the current working directory to where the file is located in order to download it :)

retrbinary simply will get the file from the server and store in your local machine using the same name it had on the server :)

Do not forget to change Server IP argument to your server's ip

and Voila that's it.

Share:
12,827
Big fat .BAT
Author by

Big fat .BAT

Updated on June 04, 2022

Comments

  • Big fat .BAT
    Big fat .BAT almost 2 years

    I am trying to download a file from my FTP server to a specific folder, without a GUI. This is what I have so far, but it does nothing,

    import urllib
    urllib.urlretrieve('ftp://USERNAME:[email protected]/File path/', 'FILENAME')