如何通过 FTP 下载文件并仅在文件不存在时将其保存在本地?
How to download a file via FTP and save it locally only if it does not exist already?
所以,我正在从 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 才能正常工作。如上所述,将 open() 与 mode = 'x' 一起使用,我收到以下错误消息:"FileExistsError: [Errno 17] File exists"
错误处理是可行的方法,还是我缺少一个巧妙的技巧?
我找到了以下解决方案:
filenames_ftp = ftp.nlst()
filenames_loc = os.listdir("C:\Financial Data\")
filenames = list(set(filenames_ftp) - set(filenames_loc))
所以,我正在从 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 才能正常工作。如上所述,将 open() 与 mode = 'x' 一起使用,我收到以下错误消息:"FileExistsError: [Errno 17] File exists"
错误处理是可行的方法,还是我缺少一个巧妙的技巧?
我找到了以下解决方案:
filenames_ftp = ftp.nlst()
filenames_loc = os.listdir("C:\Financial Data\")
filenames = list(set(filenames_ftp) - set(filenames_loc))