我只想用下面的 Python 编程代码通过 FTP 下载昨天的文件,下面的代码下载所有文件。我想根据昨天的日期检查代码中的最后修改时间戳,并仅自动下载昨天的文件。我真的需要帮助并感谢任何建议:import ftplibimport osfrom datetime import date from dateutil import parserFTP_HOST = "Remote IP"FTP_USER = "Username"FTP_PASS = "Password"# some utility functions that we gonna needdef get_size_format(n, suffix="B"): # converts bytes to scaled format (e.g KB, MB, etc.) for unit in ["", "K", "M", "G", "T", "P"]: if n < 1024: return f"{n:.2f}{unit}{suffix}" n /= 1024def get_datetime_format(date_time): # convert to datetime object date_time = datetime.strptime(date_time, "%Y%m%d%H%M%S") # convert to human readable date time string return date_time.strftime("%Y/%m/%d %H:%M:%S") # initialize FTP sessionftp = ftplib.FTP(FTP_HOST, FTP_USER, FTP_PASS)# force UTF-8 encodingftp.encoding = "utf-8"# print the welcome messageprint(ftp.getwelcome())# change the current working directory to 'pub' folder and 'maps' subfolderftp.cwd("RemoteDirectory")print("*"*50, "NLST", "*"*50)print("{:20} {:19}".format("File_Name", "last_modified"))for file_data in ftp.mlsd(): file_name,meta = file_data # convert it to human readable format (i.e in 'KB', 'MB', etc) last_modified = get_datetime_format(meta.get("modify")) try: ftp.cwd(file_name) except Exception as e: ftp.voidcmd("TYPE I") last_modified = get_datetime_format(meta.get("modify")) print(f"{file_name:20} {last_modified:19}") ftp.retrbinary("RETR " + file_name, open(file_name, 'wb').write)# quit and close the connectionftp.quit()
1 回答
海绵宝宝撒
TA贡献1809条经验 获得超8个赞
基于Python Datetime: All Items From Yesterday,这应该是:
yesterday = date.today() - timedelta(days=1)
for file_data in ftp.mlsd():
file_name,meta = file_data
last_modified = datetime.strptime(meta.get("modify"), "%Y%m%d%H%M%S")
if last_modified.date() == yesterday:
ftp.retrbinary("RETR " + file_name, open(file_name, 'wb').write)
如果服务器不支持MLSD命令,您将不得不使用效率较低的选项LIST或MDTM。看:
如果文件在最后一个 N 小时前添加到 FTP 服务器,Python 从 FTP 服务器下载文件?
如何使用 Python ftplib 获取 FTP 文件的修改时间
添加回答
举报
0/150
提交
取消
