Search code examples
pythondictionarytext-files

Open textfile and get the data behind the colon in Python


This is my Example list for you which is stored in a textfile:

DEVICE:           Test

HW-RELEASE:       Test

SERIAL-NUMBER:    Test

MAC-ADDRESS:      Test

IP-ADDRESS:       Test

IP-NETMASK:       Test

INTRANET-ADDRESS: Test

INTRANETMASK:     Test

VERSION:          Test

NAME:             Test

CONFIG-STATUS:    Test

FIRMWARE-STATUS:  Test

HW-MASK:          Test

FEATUREWORD:      Test

REGISTERED-WORD:  Test

FEATURE-LIST:     Test

FEATURE-LIST:     Test

FEATURE-LIST:     Test

FEATURE-LIST:     Test

FEATURE-LIST:     Test

FEATURE-LIST:     Test

FEATURE-LIST:     Test

FEATURE-LIST:     Test

FEATURE-LIST:     Test

TIME:            Test

HTTP-PORT:       Test

HTTPS-PORT:       Test

TELNET-PORT:      Test

TELNET-SSL-PORT:  Test

SSH-PORT:         Test

SNMP-PORT:        Test

TFTP-PORT:        Test

LOCATION:         Test

COUNTRY-CODE:     Test

COMMENT:          Test

MYVPN:            Test

MYVPN-HOSTNAME:   Test

EXTENDED-NAME:    Test

So I want to output the data behind the colon but always only one line of it. I want to define this line via a dictionary in the script so that I can for example only enter "Device" and it gives me the name after the colon so that the names in front of the colon should act as a key. As I do the whole instead I only know roughly what I have thought up so far. Unfortunately this code doesn't work as I would like it to:

data = {}

with open('C:/example/example/example/example/example.txt') as fh:
    for line in fh:
        key, value = line.strip().split(':', 1)
        data[key] = value

for x in data:
    print(x)

Output from this code is:

ValueError: not enough values to unpack (expected 2, got 1)

What I expect is when I define something like:

x = data["DEVICE"]

it should output its value which is obviously "Test"


Solution

  • First, could you try print what is in line?

    If it is as expected (i.e. contain DEVICE: Test), make sure the whitespace handled correctly as follows.

    for line in fh:
        if line.strip(): # Ignore blank lines
            key, value = [x.strip() for x in line.strip().split(':', 1)]
            ...