Uploading to an FTP site using python

Tuesday, 06 January 2009 14:36
Here is a short tutorial for you. Not so much a tutorials as a reminder guide for me as to how to upload to an FTP site using python. Copy and paste the code below into a .py file, and adjust the username/password/site given in the tutorial / example below accordingly.

from ftplib import FTP
import os

ftp = FTP('ftp.example.com', 'username', 'password') #Sets the ftp details
ftp.login #Logs into the ftp server
#ftp.retrlines('LIST') #Lists the contents of the current directory in ftp
ftp.cwd('uploads') #Changes the ftp directory
file_to_upload = open('c:/files_to_upload/certification/urls.py')
ftp.storlines('STOR filename', file_to_upload)

ftp.close()


Its also worth noting that you could make it do this as part of a for loop, then looks through all the files in turn and just uploads them all.
def look_for_files(add_path):
for items in os.walk(add_path):
path = items[0].replace('\\', '/')
filename = items[1]

In this tutorial I use the replace just to save errors with '\' (the escape character), as windows can manage filenames that have the slash in either direction, but unix really has a hard time. Anyway, happy trails.
Last Updated ( Tuesday, 06 January 2009 14:46 )
 
Sitemap