Aim
Aim

Reputation: 487

Extract the value of a variable from a text file

Following is the snippet of the text file (txt.toml):

value = 10.0
base = 14.0
outcome = 20.0
numbers = [12.0, 20.0]
input = false
Scheme = "default"
sigma = [1, 8, 11, 5]

I want to access the value of the variable "base". I tried the following solution from here:

variable = {}
with open('txt.toml', 'r') as file:
    for line in file:
        name, value = line.replace(' ', '').strip('=')
        variable[name] = value
        
print(variable['base'])

Following error is thrown:

ValueError: too many values to unpack (expected 2)

I am not able to fix this error. How can the value stored in the variable "base" be accessed?

Upvotes: 0

Views: 1636

Answers (4)

Niel Godfrey P. Ponciano
Niel Godfrey P. Ponciano

Reputation: 10709

You can use str.partition() to extract the name and the value part separated by an "=". Then you can use str.strip() to remove the whitespaces.

variable = {}
with open('txt.toml', 'r') as file:
    for line in file:
        name, _, value = line.partition('=')
        variable[name.strip()] = value.strip()
        
print(variable['base'])
$ python3 src.py 
14.0

This solution will work even if you have spaces in your source data and even if you have multiple equal "=" signs in your values

txt.toml

...
Scheme = "default value here = (12 == 12.0)"
...

code

...
print(variable['Scheme'])

output

$ python3 src.py 
"default value here = (12 == 12.0)"

Upvotes: 1

theunknownSAI
theunknownSAI

Reputation: 330

with open("txt.toml") as fd:
    lines = fd.read().splitlines()
lines = [line.split("=") for line in lines]
result =  {i[0].strip() : i[1].strip() for i in lines}
print(result)
print(result['base'])

Upvotes: 0

user15801675
user15801675

Reputation:

You need to split the string and not strip the string. split returns a list and strip() returns a string with the required substring removed from either side of the string.

.split will split the string into a list based on the delimiter and .strip() strips the string from the starting and beginning of the string.

variable = {}
with open('txt.toml', 'r') as file:
    for line in file:
        name, value = line.replace(' ', '').split('=')
        variable[name] = value
        
print(variable['base'])

Upvotes: 1

I'mahdi
I'mahdi

Reputation: 24049

use split instead of strip.

try this:

variable = {}
with open('txt.toml', 'r') as file:
    for line in file:
        name, value = line.replace(' ', '').split('=')
        variable[name] = value
        

variable

output:

{'value': '10.0\n',
 'base': '14.0\n',
 'outcome': '20.0\n',
 'numbers': '[12.0,20.0]\n',
 'input': 'false\n',
 'Scheme': '"default"\n',
 'sigma': '[1,8,11,5]'}

Upvotes: 2

Related Questions