Python - Import formatted lines as indexed list objects

Viewed 35

I am writing a minor OP5 plugin in Python 2.7 (version is out of my hands) that iterates over a multidimensional list that verifies fallback zip downloads have gone as they should.

Up until now I have put each host with their IP address in a multidimensional list looking like (cut short for brevity):

fallback = [
    ["host1", "192.168.1.3"],
    ["host2", "192.168.15.59"]
    ]

...and so on.

This lets me iterate through fallback[i] and use that along with fallback[i][1] for the IP address, the rest of the script uses both of these informations for various tasks and string manipulations. The script as it is now is mechanically sound but relies on availability of these indexes.

There is however a hidden file (.fallbackinfo) containing the same information for another script but it is written for perl, same as the script that uses that file as a source.

The file looks like this:

@hosts = (
    ["host1", "192.168.1.3", "type of firmware", "subfolder"],
    ["host2", "192.168.15.59", "type of firmware", "subfolder"],
);

I wish to import this into an iterable multidimensional list in my Python script, but am getting incredibly stuck.

My current attempt is the closest I have gotten:

with open("/home/runninguser/.fallbackinfo") as f:
    lines = []
    for line in f:
        lines.append(line.rstrip().strip())
    fallback = lines[1:len(lines)-1]

This has successfully made the list look as I want it, but all lines get imported as str objects. I have attempted to use list() to force the object to become a list but most of the time, that makes each character in the lines to become a list object instead. The network in question is cut off from internet access so I have to rely on built-in modules. My interpretation is that since it is formatted as a list, it should somehow be able to be interpreted as a list.

Can this be done at all, and if so, how?

1 Answers

You can use the json package (built-in) to achieve this:

import json

with open("/home/runninguser/.fallbackinfo") as f:
    # For each line
    for line in f:
        # If the line starts with a bracket
        if line.strip()[0] == "[":
            # Print the line after removing spaces in front and the comma in the back 
            # and converting it into a list
            print(json.loads(line.strip().rstrip(",")))

If you now use the type() function, you will see the list-formatted strings are now <class 'list'>

Related