Search code examples
pythondictionarytextiovisa

How do I dump text file contents into dictionary


Hi I'm using python 3 on mac and I'm trying to create a generic program to communicate with a range of different multimeters dependent on which text file is loaded. For example, I want a dictionary that will look something like this:

prog_key  = {"DC_Volts":"FUNC:DC V","AC_Volts":"FUNC:AC V"...} #just an example

This will eventually be used in conjunction with the pyvisa library in order to send commands to a meter.

So, in order to make my program generic, I want this dictionary:

prog_key = {}

to load a text file which has the following contents:

"DC_Volt”:”FUNC:VOLT DC”,
"DC_Curr”:”FUNC:CURR DC”,
"AC_Volt”:”FUNC:VOLT AC”,
"AC_Curr”:”FUNC:CURR AC”,
"Res_2”:”FUNC:RES”,
"Res_4”:”FUNC:RES 4”,
"Freq”:”FUNC:FREQ”,
"Cap”:”FUNC:CAP”,
"Temp”:”FUNC:TEMP”,
"Diode”:”FUNC:DIO”,
“Meas”:”MEAS:IMM”

As I will have it ready-formatted in the text file, I literally just want to dump it in the dictionary (all quotation marks, colons and commas will be in place). I'm doing it this way as different meters will have different commands, so I can just load a different text file if I'm using a different meter.

Is the fact that my commands have colons gonna cause any problems?

If theres a better way, I don't mind reformatting my text file. The main thing is that I make all of my text files following the same trend, doesn't really matter what that trent is as long as it works!

Thanks

Edit: those are indeed meant to be straight quotes


Solution

  • I think perhaps a better way to format the file (to avoid dealing with comma line delimiters and colon field delimiters) is CSV. For example,

    "DC_Volt","FUNC:VOLT DC"
    "DC_Curr","FUNC:CURR DC"
    "AC_Volt","FUNC:VOLT AC"
    

    This would allow you to read into your dictionary as follows:

    import csv
    
    my_dict = {}
    
    with open('myfile.csv', 'r') as f:
      for line in csv.reader(f):
        my_dict[line[0]] = line[1]
    

    EDIT: Like @ShadowRanger suggested, this could be better for JSON than CSV. (It would allow you to keep your key-value format).

    The file could look like:

    {
      "DC_Volt":"FUNC:VOLT DC",
      "DC_Curr":"FUNC:CURR DC",
      "AC_Volt":"FUNC:VOLT AC"
    }
    

    and you code could be:

    import json
    
    with open('myfile.json', 'r') as f:
      j = json.load(f)