【问题标题】:How to download a file via FTP and save it locally only if it does not exist already?如果文件不存在,如何通过 FTP 下载文件并将其保存在本地?
【发布时间】:2016-08-16 13:45:12
【问题描述】:

所以,我正在从 ftp 服务器下载一些数据文件。我需要每天进入并检索新文件并将它们保存在我的电脑上,但只有新文件。

到目前为止的代码:

from ftplib import FTP
import os

ftp = FTP('ftp.example.com')
ftp.login()
ftp.retrlines('LIST')
filenames = ftp.nlst()

for filename in filenames:
    if filename not in ['..', '.']:
        local_filename = os.path.join('C:\\Financial Data\\', filename)
        file = open(local_filename, mode = 'x')
        ftp.retrbinary('RETR '+ filename, file.write)

我正在考虑使用if not os.path.exists(),但我需要 os.path.joint 才能工作。如上所述使用带有 mode = 'x' 的 open() ,我收到以下错误消息:“FileExistsError: [Errno 17] File exists”

错误处理是要走的路,还是我错过了一个巧妙的技巧?

【问题讨论】:

    标签: file python-3.x ftplib


    【解决方案1】:

    我找到了以下解决方案:

    filenames_ftp = ftp.nlst()
    filenames_loc = os.listdir("C:\\Financial Data\\")
    filenames = list(set(filenames_ftp) - set(filenames_loc))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 2018-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多