亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Python 中使用 FTP 僅下載昨天的文件

在 Python 中使用 FTP 僅下載昨天的文件

阿波羅的戰車 2023-06-20 16:38:03
我只想用下面的 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命令,您將不得不使用效率較低的選項LISTMDTM??矗?/p>

  • 如果文件在最后一個 N 小時前添加到 FTP 服務器,Python 從 FTP 服務器下載文件?

  • 如何使用 Python ftplib 獲取 FTP 文件的修改時間


查看完整回答
反對 回復 2023-06-20
  • 1 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號