Search code examples
pythonftpftplib

Ftplib download zip file attempts fail ([Errno 13] Permission denied: 'C:\\Users\\kbrab\\Desktop\\2019\\test.zip)


I have been trying to set up an automated python script to download files from a remote FTP server to a local machine. I was able to establish a connection, navigate to the directory however when attempting to download the specific zip file I get an error.

[Errno 13] Permission denied: 'C:\Users\kbrab\Desktop\2019\test.zip'

I have tried Running IDLE as an administrator, I have also checked to make sure the local path directory is created and correct. Checking Other similar posts that seemed to be the issue. The FTP server is TLS/SSL Implicit encryption, the python file is being run on a windows VM.

def checkKindred():
    time = a_day_in_previous_month()
    print(time)
    lines = []
    ftp_client.cwd('/kindred/')
    print("Current directory: " + ftp_client.pwd())
    ftp_client.retrlines('NLST',lines.append)
    nameCh = ("Attrition_"+str(time))
    for line in lines:
        if nameCh == line[:17]:
            print("found match")
            print(line)
            fileName = line
            unpackKindred(fileName,time)

def unpackKindred(name,time):
    local_path = "C:\\Users\\kbrab\\Desktop"
    local_path = os.path.join(local_path, str(time)[:4],"Attrition_2019-04-30.zip")
    if not os.path.exists(local_path):
        os.makedirs(local_path)
    try:
        filenames = ftp_client.nlst()
        ftp_client.retrbinary('RETR '+name, open(local_path, 'wb').write)      
    except Exception as e:
        print('Failed to download from ftp: '+ str(e))

The code is now working through martin's insight, adding corrected code below:

def unpackKindred(name,time):
    local_path = "C:\\Users\\kbrab\\Desktop"
    local_path = os.path.join(local_path, str(time)[:4])
    if not os.path.exists(local_path):
        os.makedirs(local_path)
    filename = os.path.join(local_path, name)
    file = open(filename, "wb")
    ftp_client.retrbinary("retr " + name, file.write)

Solution

  • This creates a folder C:\Users\kbrab\Desktop\2019\test.zip:

    if not os.path.exists(local_path):
        os.makedirs(local_path)
    

    And this tries to treat the folder as if it were a file:

    ftp_client.retrbinary('RETR '+name, open(local_path, 'wb').write)