Home > Software engineering >  Extract a section in other file using python
Extract a section in other file using python

Time:07-21

I am trying to extract a section ModeName

I am using the following example code using get function

test_dict = {
    "ModeName":1, "Measurement",
    }

x = test_dict.get("ModeName")
print(x)

The above function just gives me 1. Is there any way to get complete ModeName?

CodePudding user response:

Parse file to dictionary

with open('a.txt', 'r') as f:
    test_dict  = {}
    for line in f:
        line = line.rstrip().split(':')                 # split on ':' after removing whitespace at end of line
        test_dict[line[0].strip()] = line[1].lstrip()   # remove whitespace around key and 
                                                        # left space before value
        
# Show results
print(test_dict.get('ModeName'))                        # Output: 1," Measurement"

File a.txt

ModeName : 1," Measurement"
    

CodePudding user response:

The issue with the example that you shared is with the usage of dictionary.

Valid usage would be

test_dict = {
    "ModeName":[1, "Measurement"],
    }

x = test_dict.get("ModeName")
print(x)

This will print the value [1, "Measurement"] as the value of x

  • Related