Luis Henrique
Luis Henrique

Reputation: 771

Read file and filter values with python

I have an array filled with values from a python-read .txt file, I want to break the information from that file with only what interests me, which are the un commented values, srv2 and srv3

SCRIPT

# value filter without comments
outfinally = []
outfinally = [re.split(r'\s\s+|\s*#\s*|\b\d+\b',line) for line in output[0].splitlines()]

for line in outfinally:
    print(line)

ARCHIVE

########################################################################
#
#       Licensed Materials
#
#
#       (C) Copyright. All Rights Reserved
#
#
#       ========================================================
#       Module Information:
#
#       DESCRIPTION:
#       ping.file
#
######################################################################
#srv1       300
10.10.10.1  300
srv2        300
srv3        300

OUTPUT

['', '========================================================']
['', 'Module Information:']
['', '']
['', 'DESCRIPTION:']
['', 'ping.file']
['', '']
['srv2\t', '']
['srv3\t', '']

DESERIED OUTPUT

srv2
srv3

Upvotes: 0

Views: 92

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

There is no need for a regex here, just keep the non-empty lines starting with a letter, and keep the first word:

test = """
#       ping.file
#
######################################################################

#srv1       300
10.10.10.1  300
srv2        300
srv3        300
srv4   # comments
"""

lines = [line.split()[0] for line in test.splitlines() if line and line[0].isalpha()]
print(lines)
# ['srv2', 'srv3', 'srv4']

Or if you want it like this:

print('\n'.join(lines))

Output:

srv2
srv3
srv4

Upvotes: 1

Related Questions