从 Python 中的 FTP 文件夹(文件名有空格)获取最新文件

Getting the latest files from FTP folder (filename having spaces) in Python

我有一个要求,我必须从 FTP 文件夹中提取最新的文件,问题是文件名有空格并且文件名有特定的模式。 下面是我实现的代码:

import sys
from ftplib import FTP
import os
import socket
import time
import pandas as pd
import numpy as np
from glob import glob
import datetime as dt
from __future__ import with_statement

ftp = FTP('')
ftp.login('','')
ftp.cwd('')
ftp.retrlines('LIST')

filematch='*Elig.xlsx'
downloaded = []

for filename in ftp.nlst(filematch):
  fhandle=open(filename, 'wb')
  print 'Getting ' + filename
  ftp.retrbinary('RETR '+ filename, fhandle.write)
  fhandle.close()
  downloaded.append(filename)

ftp.quit()

我知道我可以将一个空列表附加到 ftp.dir() 命令,但是由于文件名有空格,我无法以正确的方式拆分它并选择该类型的最新文件我在上面提到过。

任何帮助都会很棒。

问题是 FTP "LIST" 命令 returns 人类文本,格式取决于 FTP 服务器实现。

使用 PyFilesystem(代替标准 ftplib)及其 API 将提供 "list" API(搜索 "walk"),提供文件的 Pythonic 结构和目录列表托管在 FTP 服务器中。

http://pyfilesystem2.readthedocs.io/en/latest/index.html

如果 FTP 服务器支持,您可以通过发送 MDTM 命令获取文件 mtime,并相应地对 FTP 服务器上的文件进行排序。

def get_newest_files(ftp, limit=None):
    """Retrieves newest files from the FTP connection.

    :ftp: The FTP connection to use.
    :limit: Abort after yielding this amount of files.
    """

    files = []

    # Decorate files with mtime.
    for filename in ftp.nlst():
        response = ftp.sendcmd('MDTM {}'.format(filename))
        _, mtime = response.split()
        files.append((mtime, filename))

    # Sort files by mtime and break after limit is reached.
    for index, decorated_filename in enumerate(sorted(files, reverse=True)):
        if limit is not None and index >= limit:
            break

        _, filename = decorated_filename  # Undecorate
        yield filename


downloaded = []

# Retrieves the newest file from the FTP server.
for filename in get_newest_files(ftp, limit=1):
    print 'Getting ' + filename

    with open(filename, 'wb') as file:
        ftp.retrbinary('RETR '+ filename, file.write)

    downloaded.append(filename)