Search code examples
pythonserverftpftplib

Removing files using python from a server using FTP


I’m having a hard time with this simple script. It’s giving me an error of file or directory not found but the file is there. Script below I’ve masked user and pass plus FTP site

Here is my script

from ftplib import FTP
ftp = FTP('ftp.domain.ca')
pas = str('PASSWORD')
ftp.login(user = 'user', passwd=pas)
ftp.cwd('/public_html/')

filepaths = open('errorstest.csv', 'rb')

for j in filepaths:
    print(j)
    ftp.delete(str(j))
ftp.quit()

The funny thing tho is if I slight change the script to have ftp.delete() it finds the file and deletes it. So modified to be like this:

from ftplib import FTP


ftp = FTP('ftp.domain.ca')
pas = str('PASSWORD')
ftp.login(user = 'user', passwd=pas)
ftp.cwd('/public_html/')
ftp.delete(<file path>)
ftp.quit()

I’m trying to read this from a csv file. What am I doing wrong?


Solution

  • Whatever you have showed seems to be fine. But could you try this?

    from ftplib import FTP
    
    ftp = FTP(host)
    ftp.login(username, password)
    ftp.cwd('/public_html/')
    print(ftp.pwd())
    print(ftp.nlst())
    with open('errorstest.csv') as file:
        for line in file:   
            if line.strip():
                ftp.delete(line.strip())
    
    print(ftp.nlst())