Search code examples
pythonftplib

Delete some csv files from FTP Server using ftplib


I am trying to delete some csv files from a ftp server. Uses ftplib library. The files are not getting deleted from the server. I have read-write access to the server. No error messages even showing. I have around 20 files to delete, I can printout the filenames successfully as well.

 dir_files = []  # to store all files in the root
 try:
     ftp = ftplib.FTP(os.environ.get("TIENKANG_HOST"))  # port is 21 by default
     ftp.login(
         user=os.environ.get("TIENKANG_USER"), passwd=os.environ.get("TIENKANG_PASS")
     )
     ftp.encoding = "unicode_escape"
     ftp.dir(dir_files.append)
     for file_info in dir_files:
         if "DATA_collection" in file_info:
             if filename not in file_info:
                 old_filename = file_info.split(" ")[-1]
                 if old_filename[-3:] == "csv":
                     # data can be exported to db if necessary before removing
                     # print(old_filename)
                     ftp.delete(old_filename)
 except Exception as e:
     print(e)
 finally:
     ftp.quit()

My files are in root of the server. below given how I sort out filenames. (unfortunately ftp.nlst leads to error)

FileZilla root folder view: Filezilla view of root folder

How I sort out filename: How I sort out filename


Solution

  • I had to use ftp.encoding = "unicode_escape" , to get all filenames in the ftp server. Without changing the encoding I gets error since there is machine related files exist in the ftp server that is not in standard unicode encoding.

    So, before deleting I changed encoding back to ftp.encoding = "utf-8" and all went prefectly.

    Solution will be as follows,

     dir_files = []  
     try:
         ftp = ftplib.FTP(os.environ.get("TIENKANG_HOST"))  # port is 21 by default
         ftp.login(
             user=os.environ.get("TIENKANG_USER"), passwd=os.environ.get("TIENKANG_PASS")
         )
         ftp.encoding = "unicode_escape"
         ftp.dir(dir_files.append)
         # Set encoding to utf-8, so the file can be found to delete
         ftp.encoding = "utf-8"
         for file_info in dir_files:
             if "DATA_collection" in file_info:
                 if filename not in file_info:
                     old_filename = file_info.split(" ")[-1]
                     if old_filename[-3:] == "csv":
                         # data can be exported to db if necessary before removing
                         ftp.delete(old_filename)
     except Exception as e:
         print(e)
     finally:
         ftp.quit()