Python Forum
Is there a more effecient way to do this ? File Names - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Is there a more effecient way to do this ? File Names (/thread-19710.html)



Is there a more effecient way to do this ? File Names - sumncguy - Jul-11-2019

I often need to loop through a list of logs and parse them.
I like to use, for instance, an ip and hostname as designations for files creation. Its just easy to look at the file and know what / who it belows too.

My question is .. is there a better way to split things apart ?

Sample data
Quote:10.10.10.10_hostname1.log
10.10.10.11_hostname2.log
10.10.10.12_hostname3.log

Existing Code
def main():
    for file in glob.glob("*.log"):
        file, fext  = os.path.splitext(file)  
        ip, hnam = file.split("_")
 
	print(file)    
	print(ip)    
	print(hnam)    


main()
Output. But his output is just check results vars will be used eleswhere in the developing program.
Quote:10.10.10.10_house
10.10.10.10
house
10.10.10.11_house2
10.10.10.11
house2
10.10.10.11_house3
10.10.10.11
house3

Thnks in advance
Sum


RE: Is there a more effecient way to do this ? File Names - metulburr - Jul-11-2019

Thats about what i would do


RE: Is there a more effecient way to do this ? File Names - DeaD_EyE - Jul-11-2019

With pathlib you have a better abstraction.

from pathlib import Path


def main(root):
    root = Path(root)
    for logfile in root.glob("*.log"):
        try:
            ip, hname = logfile.stem.split('_')
        except ValueError:
            continue
        print(ip, hname)


main('/var/log')