0

I have a file that stores variable names and values like below:

name,David
age,16
score,91.2
...

I want to write a python script that reads the file and automatically creates variables in an object without me actually doing it, something like:

self.name='David'
self.age=16
self.score=91.2

Is it possible to do that? The reason I do this is there might be files containing very different types of variables which I don't know beforehand.

jpp
  • 159,742
  • 34
  • 281
  • 339
zleung
  • 31
  • 1
  • 3
  • 4
    You can use a dictionnary to store the file values, and if you want to assign them to an object, just use `for name, value in dict_.items(): setattr(self, name, value)`. – Delgan Jul 05 '18 at 15:57
  • 3
    It's usually a bad idea to create names dynamically. You'd better store them in a `dict`. – iBug Jul 05 '18 at 16:03
  • 3
    Assuming you did this, what would be the next step? How will you use those variables in the rest of the code? – tobias_k Jul 05 '18 at 16:03
  • @CharlesDuffy, My apologies, I reread the question and the last sentence proves you are right.. `The reason I do this is there might be files containing very different types of variables ...` It's clear these are arbitrary. They need to go in a `dict`. – jpp Jul 05 '18 at 16:22

3 Answers3

2

The reason I do this is there might be files containing very different types of variables which I don't know beforehand.

If this is the primary reason, you should use a dictionary. There's no better way. See the marked duplicates.


Original solution

While it's usually recommended to keep like variables in a dictionary, if the variables describe a class instance there is no harm in assigning them directly. If the dictionary keys are arbitrary, I recommend you pass the dictionary to the class instead.

As per @Delgan's comment, you can create a dictionary from your text file and then use setattr while iterating dictionary items. Below is a solution which uses the csv module and wraps the logic in a function.

import csv

def add_attributes(obj, fn):

    # create dictionary from text file
    with open(fn, 'r') as fin:
        d = dict(csv.reader(fin))

    # iterate dictionary and add attributes
    for name, value in d.items():
        setattr(obj, name, value)

    return obj

class myClass():
    def __init__(self):
        pass

A = myClass()

add_attributes(A, 'file.csv')

print(A.age)  # 16
jpp
  • 159,742
  • 34
  • 281
  • 339
1

I recommend cleaner ways to store your data (like JSON or even python's pickle module). But this is out of the context of this answer. Assuming, you want to use your data format, you could read your file like this:

my_object = xyz()
variables_file = open("variables.txt", "r")
for line in variables_file:
    line = line.rstrip("\n") # remove the linebreak at the end of each line
    line = line.split(",") # split the line at the comma -> generates a list
    setattr(my_object, line[0], line[1]) # sets the variable as attribute of my_object
print("And the name is: "+my_object.name)+"!!!")

A better way is the use of dictionaries which is a more pythonic way than the java way:

configs = {}

And assign values like:

configs["name"] = "David"

or do it dynamically by iterating through the file like in the example above, just without setattr and with:

configs[line[0]] = line[1]
halfer
  • 19,824
  • 17
  • 99
  • 186
fameman
  • 3,451
  • 1
  • 19
  • 31
-1

When you create a Class, you should know how many variables your Class will have.

It is a bad idea to dynamically create new variables for an object in a Class because you can't do operations with variables.

e.g. Suppose your class has variables name,age,marks,address. You can perform operations on this because you know the variables already.

But if you try to store variables dynamically, then you have no idea which variables are present and you can't perform operations on them.

If you only want to display the variable and its value present in a file, then you can use a dictionary to store the variables with their respective values. After all the variables are stored in the dictionary, you can display the variables and their values:

dict={}
with open('filename.txt') as f:
data = f.readlines()
for i in data:
    i = i.rstrip()
    inner_data = i.split(',')
    variable = inner_data[0]
    value = inner_data[1]
    dict.update({variable:value})

print(dict)

This will print all the variables and thier value in the file.

But the file should contain variables and values in the following format:

name,Sam
age,10
address,Mumbai
mobile_no,199204099
....
....
jkdev
  • 11,360
  • 15
  • 54
  • 77
swapnil
  • 92
  • 5