Man*_*ani 7 python ftplib python-2.7
我有一个要求,我必须从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()
Run Code Online (Sandbox Code Playgroud)
我知道我可以在ftp.dir()命令中添加一个空列表,但由于文件名有空格,我无法以正确的方式拆分它并选择我上面提到的类型的最新文件.
任何帮助都会很棒.
如果 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)
Run Code Online (Sandbox Code Playgroud)