Fizza Hussain
Fizza Hussain

Reputation: 23

Extract data from a field in a text file in Python

I am new to Python. I want to know what is the best way to extract data from a field in a text file?

My text file saves the information of a network. It looks like this:

Name: Machine_1 Status: On IP:10.0.0.1
Name: Machine_2 Status: On IP:10.0.0.2
Network_name: Private Router_name: router1 Router_ID=3568
Subnet: Tenant A

The file is not very structured. It cannot even be expressed as a CSV file due to non-homogeneous nature of rows i.e. all of them do not have the same column identifiers.

What I want to do is to be able to get the value of any field I want e.g. Router_ID.

Please help me find a solution to this.

Thanks.

Upvotes: 1

Views: 1579

Answers (1)

Jose Varez
Jose Varez

Reputation: 2077

You could use regular expressions to scan through your file. You'd have to define a regular expression for each field you want to extract. For example:

import re
data = """Name: Machine_1 Status: On IP:10.0.0.1
Name: Machine_2 Status: On IP:10.0.0.2
Network_name: Private Router_name: router1 Router_ID=3568
Subnet: Tenant A"""
for line in data.split('\n'):
    ip = re.match('.*IP:(\d+.\d+.\d+.\d+)', line)
    rname = re.match('.*Router_name: (\w+)', line)
    if ip and ip.lastindex > 0: 
        print(ip.group(1))
    if rname and rname.lastindex > 0:
        print(rname.group(1))

Output:

10.0.0.1
10.0.0.2
router1

Upvotes: 1

Related Questions