Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

import ftplib

import urllib2

import os

import logging

logger = logging.getLogger('ftpuploader')

hdlr = logging.FileHandler('ftplog.log')

formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

hdlr.setFormatter(formatter)

logger.addHandler(hdlr)

logger.setLevel(logging.INFO)

FTPADDR = "some ftp address"

def upload_to_ftp(con, filepath):

    try:

        f = open(filepath,'rb')                # file to send

        con.storbinary('STOR '+ filepath, f)         # Send the file

        f.close()                                # Close file and FTP

        logger.info('File successfully uploaded to '+ FTPADDR)

    except, e:

        logger.error('Failed to upload to FTP: '+ str(e))

I am getting a syntax error. Kindly let me know where is the error.

1 Answer

0 votes
by (108k points)
edited by

You just need to set which kind of exception you want to catch. 

Try to execute the below code:

try:

    with open(filepath,'rb') as f:

        con.storbinary('STOR '+ filepath, f)

    logger.info('File successfully uploaded to '+ FTPADDR)

except Exception, e: # work on python 2.x

    logger.error('Failed to upload to ftp: '+ str(e))

In Python 3.x, you have to use:

 except Exception as e 

Instead of the below code: 

except Exception, e:

This is how you need to write:

try:

    with open(filepath,'rb') as f:

        con.storbinary('STOR '+ filepath, f)

    logger.info('File successfully uploaded to '+ FTPADDR)

except Exception as e: # work on python 3.x

    logger.error('Failed to upload to ftp: '+ str(e))

Related questions

Browse Categories

...