Python Script Uploading files via FTP
Use ftplib
, you can write it like this:
import ftplibsession = ftplib.FTP('server.address.com','USERNAME','PASSWORD')file = open('kitten.jpg','rb') # file to sendsession.storbinary('STOR kitten.jpg', file) # send the filefile.close() # close file and FTPsession.quit()
Use ftplib.FTP_TLS
instead if you FTP host requires TLS.
To retrieve it, you can use urllib.retrieve
:
import urllib urllib.urlretrieve('ftp://server/path/to/file', 'file')
EDIT:
To find out the current directory, use FTP.pwd()
:
FTP.pwd(): Return the pathname of the current directory on the server.
To change the directory, use FTP.cwd(pathname)
:
FTP.cwd(pathname): Set the current directory on the server.
ftplib now supports context managers so I guess it can be made even easier
from ftplib import FTPfrom pathlib import Pathfile_path = Path('kitten.jpg')with FTP('server.address.com', 'USER', 'PWD') as ftp, open(file_path, 'rb') as file: ftp.storbinary(f'STOR {file_path.name}', file)
No need to close the file or the session
You will most likely want to use the ftplib module for python
import ftplib ftp = ftplib.FTP() host = "ftp.site.uk" port = 21 ftp.connect(host, port) print (ftp.getwelcome()) try: print ("Logging in...") ftp.login("yourusername", "yourpassword") except: "failed to login"
This logs you into an FTP server. What you do from there is up to you. Your question doesnt indicate any other operations that really need doing.