Python FTP服务器下载文件名中包含特定关键字的最新文件 [英] Python FTP server download Latest File with specific keywords in filename

查看:85
本文介绍了Python FTP服务器下载文件名中包含特定关键字的最新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用python从FTP服务器下载最新文件.我能够连接到服务器并下载特定目录中的所有文件,但是我不知道如何在主题中查找带有特定关键字的最新文件.

I want to download the most recent file from FTP server with python. I am able to connect to the server and download all the files in a particular directory but I do not know how to find the most recent file with the specific keyword in the subject.

以下是我正在使用的代码.但是它将返回所有带有* .png键名的文件.我不知道如何在这里应用os.path.getctime来获取最新文件.这就是我想要的所有帮助.

Following is the code i am using. But it returns all the files with *.png keyname. I do not know how to apply os.path.getctime here to get the latest file.Thats all the help i wanted.

        import ftplib
        import os

        ftp = ftplib.FTP('test.rebex.net', 'demo','password')
        ftp.retrlines('LIST')

        ftp.cwd("/pub")

        ftp.retrlines('LIST')

        ftp.cwd("example")

        ftp.retrlines('LIST')
        filematch='*.png'
        target_dir='C:/Users/muzamal.pervez/Desktop/OPD Claims'
        for filename in ftp.nlst(filematch):
            target_file_name = os.path.join(target_dir,os.path.basename(filename))
            with open(target_file_name,'wb') as fhandle:
                    ftp.retrbinary('RETR %s' %filename, fhandle.write)

推荐答案

已解决.

    import ftplib
    import os
    import time
    from dateutil import parser

    ftp = ftplib.FTP('test.rebex.net', 'demo','password')
    ftp.retrlines('LIST')

    ftp.cwd("pub")
    ftp.cwd("example")
    ftp.retrlines('LIST')

    names = ftp.nlst()
    final_names= [line for line in names if 'client' in line]

    latest_time = None
    latest_name = None

    for name in final_names:
        time = ftp.sendcmd("MDTM " + name)
        if (latest_time is None) or (time > latest_time):
            latest_name = name
            latest_time = time

    print(latest_name)
    file = open(latest_name, 'wb')
    ftp.retrbinary('RETR '+ latest_name, file.write)

这篇关于Python FTP服务器下载文件名中包含特定关键字的最新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆