Lily
Lily

Reputation: 846

Search for a variable in a file and get its value with python

I want to have some variables that are stored in a file (text file or yaml file)

for example if I have these variables stored in the file

employee = ['Tom', 'Bob','Anny']
salary = 200
managers = ['Saly','Alice']

and I want the user to enter the list name or the variable name for example

if the user entered employee and want to do some operations on the list values so the user supposed to access employee[0], employee[1] .... etc

how can I write a python script that will go to the file search for the correct variable and give the user access to its value

Thanks

Upvotes: 2

Views: 7709

Answers (2)

Levon
Levon

Reputation: 143047

This approach might be one way assuming your file contents is somewhat consistent:

Updated: I added the code necessary to parse the lists which previously wasn't provided.

The code takes all of the data in your file and assigns it to the variables as appropriate types (i.e., float and lists). The list parsing isn't particularly pretty, but it is functional.

import re
with open('data.txt') as inf:
    salary = 0
    for line in inf:
        line = line.split('=')
        line[0] = line[0].strip()
        if line[0] == 'employee':
            employee = re.sub(r'[]\[\' ]','', line[1].strip()).split(',')
        elif line[0] == 'salary':
            salary = float(line[1])
        elif line[0] == 'managers':
            managers = re.sub(r'[]\[\' ]','', line[1].strip()).split(',')

print employee
print salary
print managers

yields:

['Tom', 'Bob', 'Anny']
200.0
['Saly', 'Alice']

Upvotes: 0

dolaameng
dolaameng

Reputation: 1437

Like what @Levon said, there are several ways that allow you do that, and the best depends on your problem context. for example, you could

  1. read the file yourself by formatting it e.g., via delimiter "=" in your file
  2. use a database to store your data
  3. use pickle or shelve to serialize your variables and get them back later.
  4. put the variables in a python module and import it

Upvotes: 3

Related Questions