【问题标题】:Download log files from FTP Server using a keyword in python使用python中的关键字从FTP服务器下载日志文件
【发布时间】:2018-01-15 02:43:12
【问题描述】:

我在从 FTP 服务器获取日志文件时遇到问题。 我可以从 FTP 服务器获取单个文件。但我在获取多个文件时遇到问题,无法从中获取文件。

在我的 FTP 服务器中,我的日志文件格式类似于 LOG_NAME_DATETIME

这是我在 FTP 服务器中的文件示例。

log_sample_01-02-2018_08:00:20:119203.txt
log_sample_01-02-2018_19:00:40:113203.txt
log_sample_01-02-2018_22:00:15:112203.txt

我的日志文件中唯一的区别是time,我想通过date下载它们

这是我在程序中尝试的,但出现错误。

name = 'sample'
date = '01-02-2018'
ftp.retrbinary('RETR log_' + name + '_' + date + '*.txt', open('log.txt', 'wb').write)

我认为结尾部分的* 会做到这一点,因为在linux 命令行中,我使用cat * .txt 连接我的日志。已经尝试搜索有关我的问题的一些参考。

【问题讨论】:

标签: python-3.x ftp ftplib


【解决方案1】:

您可能必须过滤要在客户端计算机上下载的文件。 您可以列出现有文件:

fileNames = ftp.nlst()

然后根据名字下载你想要的:

for fileName in fileNames:
    currentName, currentDate, currentTime = fileName.split("_")
    if currentName == name and currentDate == date:
        ftp.retrbinary('RETR '+fileName, open('log.txt', 'wb').write)

如果文件名末尾的 endline(或 unix 中的 \n)导致问题,您可能需要在最后一行添加 .rstrip("\n") 到 fileName。

请注意,如果您的文件名中有下划线,则此确切语法不起作用。

灵感来自this github file。

【讨论】:

  • 您好先生,谢谢您的回答。我正在寻找一种方法来使用这样的文件名? log-server.net-SAMPLE-01-01-02-2018_22:00:15:112203.txt
  • 在这种情况下,您可以使用带有name = "log-server.net-SAMPLE-01-" 和date = "01-02-2018" 的代码示例。我还更新了我的示例,因为它是错误的......
猜你喜欢
  • 2012-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-21
  • 2011-03-01
  • 1970-01-01
  • 2018-07-08
相关资源
最近更新 更多