Python Forum
Is there a more effecient way to do this ? File Names
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Is there a more effecient way to do this ? File Names
#1
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
Reply
#2
Thats about what i would do
Recommended Tutorials:
Reply
#3
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')
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  rename same file names in different directories elnk 0 706 Nov-04-2022, 05:23 PM
Last Post: elnk
  Saving Excel workbook file with dataframe names Biplab1985 0 2,019 Jun-07-2020, 12:25 PM
Last Post: Biplab1985
  Details of attachment files in a msg file such as file names save into a python list klllmmm 2 5,684 Nov-12-2019, 05:59 AM
Last Post: klllmmm
  splitstring file names a by hyphen steve22020 3 3,261 Oct-30-2019, 05:39 PM
Last Post: steve22020
  How to combine file names into a list from multiple directories? python_newbie09 3 5,192 Jul-09-2019, 07:38 PM
Last Post: python_newbie09
  write each line of a text file into separate text files and save with different names Shameendra 3 2,768 Feb-20-2019, 09:07 AM
Last Post: buran
  Reading file names CertifiedPengu 1 2,263 Jan-07-2019, 06:54 PM
Last Post: Gribouillis
  temporary file names Skaperen 6 3,722 Jan-02-2019, 07:14 PM
Last Post: Skaperen
  how to increment all file names in a folder SoulsKeeper 5 6,024 Sep-10-2018, 07:59 PM
Last Post: Skaperen
  dealing with spaces in file names AceScottie 5 75,035 Jun-02-2018, 01:06 PM
Last Post: AceScottie

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020