【问题标题】:Python download a file from FTP where the filename starts with specific charactersPython 从 FTP 下载文件,其中文件名以特定字符开头
【发布时间】:2018-07-18 18:09:31
【问题描述】:

我正在尝试编写一个 python 脚本,该脚本将登录到 FTP 服务器并仅下载文件名以某些字符开头的目录中的文件。我要连接的 FTP 目录中的文件都有不同的文件名,并且都以日期/时间戳结尾,而不是像“.txt”这样的文件扩展名。 例如:

-rw-------   1 USERNAME USERNAME      1230456 Jul 18 11:02 NOTMYFILE.FILE.201807181102
-rw-------   1 USERNAME USERNAME      1230457 Jul 18 12:02 FILEINEED.FILE.201807181202
-rw-------   1 USERNAME USERNAME      1230458 Jul 18 10:02 FILEINEED.FILE.201807181002
-rw-------   1 USERNAME USERNAME      1230458 Jul 18 09:02 NOTMYFILE.FILE.201807181902

我需要告诉 python 只下载以“FILEINEED”开头的文件。

我已搜索但无法找到下载文件名以“FILEINEED”开头的文件并让它忽略以“NOTMYFILE”开头的文件的方法

以下是我目前在脚本中的内容:

from ftplib import FTP

ftp = FTP("ftp.server.url")
ftp.login(user="UserName", passwd="password123")
ftp.retrlines("LIST")

ftp.cwd("/outbox/")

感谢任何帮助!

【问题讨论】:

    标签: python file ftp


    【解决方案1】:

    您可以获得所有文件名的列表,按'FILEINEED' in filename 过滤该列表,然后对这些文件使用FTP.retrbinary

    filesineed = [filename for filename in ftp.nlst() if 'FILEINEED' in filename]
    
    # Iterate through all the filenames and retrieve them one at a time
    for filename in filesineed:
        local_filename = os.path.join(os.getcwd(), filename)
        with open(local_filename, 'wb') as f:
            print('downloading {}...'.format(filename))
            ftp.retrbinary('RETR %s' % filename, f.write)
    

    会将这些文件保存到您本地的当前工作目录。如果您想保存在其他位置,请更改 local_filename

    【讨论】:

      【解决方案2】:

      这里面有三个步骤-

      1. 通过 FTP 连接
      2. 从 FTP 获取所有文件名
      3. 使用您要下载的特定字符搜索文件

      代码写在下面-

      #Open ftp connection
      ftp = ftplib.FTP('ftp address', 'Username','Password')
      # Get All Files
      files = ftp.nlst()
      for file in files:
        if(file.startswith('abc') and file.endswith('.xyz')):
          print("Downloading..." + file)
          ftp.retrbinary("RETR " + file ,open("D:/" + file, 'wb').write)
      

      或者我们也可以像这样在文件名中搜索特定字符 -

      if 'abxy' in file:
          print(file)
          ftp.retrbinary("RETR " + file ,open("D:/" + file, 'wb').write)
      

      【讨论】:

        猜你喜欢
        • 2023-03-21
        • 1970-01-01
        • 2021-10-10
        • 2021-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多