Open textfile and get the data behind the colon in Python

Question:

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"

Asked By: Dark Shadow

||

Answers:

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)]
        ...
Answered By: Darren Christopher

Your problem lies in the format of your text file.

The empty lines between your value lines make key, value = line.strip().split(':', 1) crash. Simply reformat your text file or handle empty lines accordingly.

Answered By: Björn Böing

This is one option:

item = 'DEVICE'

filepath = '/home/will/testing/stuff.txt'

with open(filepath) as f:
    data = f.read().splitlines()
    data = [line for line in data if line != '']
    data_dict = {line.split()[0][:-1]:line.split()[1] for line in data}

print(data_dict[item])
# Test
Answered By: Dodge

You are not skipping the empty lines.

If the example you posted is correct between to “entries” there is an empty line that you are trying to split:

try:

for line in fh:
   if line:
    key, value = line.strip().split(':', 1)
    data[key] = value
Answered By: RedX
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.