Created
February 4, 2019 11:06
-
-
Save fredrikaverpil/cfb1c23424f8c776d8b547dd30b8ce88 to your computer and use it in GitHub Desktop.
FTP upload with Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Upload file to folder. | |
Note: | |
Written for Python 3.7. | |
""" | |
import os | |
import ftplib | |
FTP_ADDR = "ftp.address.com" | |
USERNAME = "username" | |
PASSWORD = "password" | |
DST_FOLDER = "someFolder" | |
SRC_FILEPATH = "kitten.jpg" | |
DST_FILENAME = "kiten2.jpg" | |
def chdir(session, dirpath): | |
"""Change to directory.""" | |
if directory_exists(session, dirpath) is False: # (or negate, whatever you prefer for readability) | |
print("Creating folder %s..." % dirpath) | |
session.mkd(dirpath) | |
print("Changing to directory %s..." % dirpath) | |
session.cwd(dirpath) | |
def directory_exists(session, dirpath): | |
"""Check if remote directory exists.""" | |
filelist = [] | |
session.retrlines('LIST',filelist.append) | |
for f in filelist: | |
if f.split()[-1] == dirpath and f.upper().startswith('D'): | |
return True | |
return False | |
def main(): | |
"""Transfer file to FTP.""" | |
# Connect | |
print("Connecting to FTP...") | |
session = ftplib.FTP(FTP_ADDR, USERNAME, PASSWORD) | |
# Change to target dir | |
chdir(session, dirpath=DST_FOLDER) | |
# Transfer file | |
print("Transferring %s and storing as %s..." % (os.path.basename(SRC_FILEPATH), DST_FILENAME)) | |
with open(SRC_FILEPATH, "rb") as file: | |
session.storbinary('STOR %s' % os.path.basename(DST_FILENAME), file) | |
print("Closing session.") | |
# Close session | |
session.quit() | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment