Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

For our daily monitoring we need to access 16 servers of a particular application and find the latest log file on one of those servers (it usually generates on the first 8).

The problem is that this code is giving me the latest file from each server instead of providing the latest log file from the entire group of servers.

Also, since this is an hourly activity, once the file is processed, it gets archived, so many of the servers don't have any log files present in them at a particular time. Due to this, while the below code is getting executed, I get - ValueError: max() arg is an empty sequence response and the code stops at server 3 if server 4 does not have any log files.

I tried adding default = 0 argument to latest_file but it gives me the error message TypeError: expected str, bytes or os.PathLike object, not int

Can you please help me out here? I am using Python 3.8 and PyCharm.

This is what I have so far :

import glob
import os
import re

paths = [r'\Server1Logs*.log',
         r'\Server2Logs*.log',
         .....
         r'\Server16Logs*.log']


for path in paths:
    list_of_files = glob.glob(path)
    latest_file = max(list_of_files, key=os.path.getctime)
    f = open(os.path.join(latest_file), "r")
    print(latest_file)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
183 views
Welcome To Ask or Share your Answers For Others

1 Answer

Create the list first and then find the max.

import glob
import os
import re

paths = [r'\Server1Logs*.log',
         r'\Server2Logs*.log',
         .....
         r'\Server16Logs*.log']

list_of_files = []
for path in paths:
    list_of_files.extend(glob.glob(path))

if list_of_files:
    latest_file = max(list_of_files, key=os.path.getctime)
    f = open(os.path.join(latest_file), "r")
    print(latest_file)
else:
    print("No log files found!")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...