我有一个要求,我必须从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()命令中添加一个空列表,但由于文件名有空格,我无法以正确的方式拆分它并选择我所指定类型的最新文件上方。
任何帮助都会很棒。
答案 0 :(得分:4)
如果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)
答案 1 :(得分:1)
问题是FTP“LIST”命令返回人类的文本,其格式取决于FTP服务器的实现。
使用PyFilesystem(代替标准的ftplib)及其API将提供一个“列表”API(搜索“walk”),它提供FTP服务器中托管的文件和目录列表的Pythonic结构。