Karl Guevarra
Karl Guevarra

Reputation: 349

Download log files from FTP Server using a keyword in python

I have a problem in getting a log files from FTP Server. I can get a single file from FTP Server. But I'm having a problem in getting multiple files and can't get files from it.

In my FTP Server I have log files with format like this LOG_NAME_DATETIME

Here are the example of my files in FTP Server.

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

The only difference in my log files are the time and I want to download them by date

This is what I tried in my program and got an error.

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

I thought the * at the end part will do it since in linux command line, I used cat * .txt in concatenating my logs. Already tried to search some reference about my problem.

Upvotes: 1

Views: 1127

Answers (1)

Fire
Fire

Reputation: 393

You will probably have to filter the files to download on the client machine. You can list the existing files:

fileNames = ftp.nlst()

And download the ones you want based on their names:

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

You might have to add a .rstrip("\n") to fileName in the last line if the the endline (or \n in unix) at the end of the file names cause problem.

Note that this exact syntax does not work if there is an underscore in your file name.

Inspired by this github file.

Upvotes: 2

Related Questions