【问题标题】:Downloading FTP Files Skipping similar files下载 FTP 文件 跳过类似文件
【发布时间】:2013-11-28 12:00:52
【问题描述】:

我正在尝试将文件从 ftp 服务器下载到我的 Python 目录。我想检查文件是否存在于我计算机中的某个位置。我想跳过现有文件,只将路径上不存在的文件复制到 My Python Directory。

当我运行脚本时,它开始下载文件。但是,它会复制存在和不存在的文件。然后它在中途断开连接。需要进行哪些修正? 我知道有类似的例子,但请让我知道为什么这不起作用。 这是我的脚本。

 class Testing():
        def __init__(self):
            import ftplib
            f = ftplib.FTP('ftp_server_path','login_name','password')
            f.cwd('new_directory')
            f.cwd('new_directory')

            import os
            for ftp_file in f.nlst():

                for filename in os.listdir("path_where_files_exist"):

                    if not (ftp_file == filename):
                        print('Downloading file: %s', ftp_file)
                        f.retrbinary('RETR '+ ftp_file ,open(ftp_file,'wb').write,rest=0)
                        break;
            f.quit()

【问题讨论】:

    标签: python ftp download


    【解决方案1】:

    这应该可以解决覆盖文件的问题。

    for ftp_file in f.nlst():
        if ftp_file not in os.listdir("path_where_files_exist"):
            print('Downloading file: %s', ftp_file)
            f.retrbinary('RETR '+ ftp_file ,open(ftp_file,'wb').write,rest=0)
            f.quit()
    

    使用 2 个循环,条件就是问题所在。 你的代码:

    for ftp_file in f.nlst():
        for filename in os.listdir("path_where_files_exist"):
            if not (ftp_file == filename):
            #some code
    

    对于一个ftp_file,它将检查每个filename。每次发现ftp_file不等于filename,就下载了。

    因此,即使文件存在,该条件也会返回目录中所有其他filename 的True,并且ftp_file 将被下载与目录中的文件一样多的次数。

    希望这会有所帮助。

    【讨论】:

    • 是的。我错过了!谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-08-18
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 2014-08-05
    • 1970-01-01
    • 2012-10-04
    • 1970-01-01
    相关资源
    最近更新 更多