2013-11-28 34 views
1

我试图从FTP服务器下载文件到我的Python目录。我想检查这些文件是否存在于我的电脑中的某个位置。我想跳过现有文件,只将路径中不存在的文件复制到My Python Directory。正在下载FTP文件跳过类似的文件

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

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

回答

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将被下载的次数与目录中文件的次数相同。

希望这会有所帮助。

+0

是的。我错过了!谢谢。 – Techidiot