Sunday, May 26, 2013

Download and/or Read Directly a File from FTP with Python

See this script below:
class Reader:
def __init__(self):
self.data = ""
def __call__(self,s):
self.data += s
ftp = ftplib.FTP("localhost")
ftp.login("username", "password")
#change ftp directory
ftp.cwd("MyJobs/dELTA_PROJECT/ftp")
filenames = []
ftp.retrlines('NLST', filenames.append)
#download to local folder
for filename in filenames:
if filename.endswith(".csv"):
local_filename = os.path.join('/tmp/', '__tmp_'+filename)
file = open(local_filename, 'wb')
ftp.retrbinary('RETR '+ filename, file.write)
file.close()
#read directly
for filename in filenames:
if filename.endswith(".csv"):
r = Reader()
ftp.retrbinary('RETR '+ filename, r)
_logger.info (r.data)
ftp.close()
view raw ftp_example.py hosted with ❤ by GitHub
Hope this help