首页 > 解决方案 > Ftplib 下载 zip 文件尝试失败([Errno 13] Permission denied: 'C:\\Users\\kbrab\\Desktop\\2019\\test.zip)

问题描述

我一直在尝试设置一个自动化的 python 脚本来将文件从远程 FTP 服务器下载到本地机器。我能够建立连接,导航到目录,但是在尝试下载特定的 zip 文件时出现错误。

[Errno 13] 权限被拒绝:'C:\Users\kbrab\Desktop\2019\test.zip'

我曾尝试以管理员身份运行 IDLE,我还检查以确保本地路径目录已创建且正确。检查似乎是问题的其他类似帖子。FTP 服务器是 TLS/SSL 隐式加密,python 文件正在 Windows 虚拟机上运行。

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))

该代码现在正在通过马丁的洞察力工作,在下面添加更正的代码:

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)

标签: pythonftpftplib

解决方案


这将创建一个文件夹 C:\Users\kbrab\Desktop\2019\test.zip

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

这试图将文件夹视为文件:

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

推荐阅读