简体   繁体   中英

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 视图

How I sort out filename: 我如何整理文件名

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM