Home > Net >  Importing data from notepad to python dictionary
Importing data from notepad to python dictionary

Time:10-29

I have notepad with data in this style:

10.0.0.1 admin admin 10.0.0.2 admin admin 10.0.0.3 admin admin

I want to take this data from notepad and import it into python dictionary where key values will be "ip":"10.0.0.1", "name":"admin","passwd":"admin" And by loop i will put those key values to netmiko to connect each device one by one. But have no clue how to convert this data from notepad to dictionary :(

CodePudding user response:

Assuming your file is really one line separated as given, and what you really want is a list of dicts, here is one option.

np = "10.0.0.1 admin admin 10.0.0.2 admin admin 10.0.0.3 admin admin"
tokens = np.split()

dicts = []
while tokens:
    dicts.append({"pass": tokens.pop(), "user": tokens.pop(), "ip": tokens.pop()})

[print(d) for d in dicts]

yielding:

➜ python np.py
{'pass': 'admin', 'user': 'admin', 'ip': '10.0.0.3'}
{'pass': 'admin', 'user': 'admin', 'ip': '10.0.0.2'}
{'pass': 'admin', 'user': 'admin', 'ip': '10.0.0.1'}

CodePudding user response:

How about reading the file into Python and then splitting it into a list and then each list item into a dict: Added a possibility of name and password missing from the text file line, leaving only the IP as a usable variable.

dir = r"C:\Users\username\Desktop\"

with open(fr"{dir}file.txt", "r") as f:
    a = f.read().splitlines()

a_list = [item.split(" ") for item in a]

for network in a_list:
    if len(network) != 3:
        network_dict = {"ip": network[0], "name": "default_name", "passwd": "default_password"}
    else:
        network_dict = {"ip": network[0], "name": network[1], "passwd": network[2]}
    #do whatever is needed with the dict here

If you want to have a directory as a variable, use raw string as such

dir = r"C:\Users\username\Desktop\"

This way you don't have to escape special characters including backslashes.

  • Related