0

How can I do this:

reader = csv.reader(open(file_path, 'rb').read().splitlines(), delimiter=";")
p = Product()

for key, row in enumerate(reader):
    f = request.POST.get('select_%s' % key) // ex. productname
    p.f = row[key] // HOW TO?, p.f should be "productname" from the variable

Hope you can helt me!

5
  • Sorry, I don't follow. What's the issue? Commented Jan 31, 2013 at 8:27
  • 1
    key is enumerated number, i.e. the row number, are you sure you want to do row[key]?? Commented Jan 31, 2013 at 8:29
  • I'm confused too. Is the problem setting an attribute on p which you only know the name of at runtime? If so, try setattr. Commented Jan 31, 2013 at 8:29
  • Sorry that i was unclear - it was the setattr function I was after .. it worked! ;) Commented Jan 31, 2013 at 8:35
  • #avasal you was right ... the result end op like this: for row in reader: p = Product() for i in range(0, len(row)): f = request.POST.get('select_%s' % i) setattr(p, f, row[i]) Commented Jan 31, 2013 at 8:49

1 Answer 1

2

Use setattr to set an attribute of an object based on a name at runtime:

reader = csv.reader(open(file_path, 'rb').read().splitlines(), delimiter=";")
p = Product()

for key, row in enumerate(reader):
    f = request.POST.get('select_%s' % key) // ex. productname
    // p.f should be "productname" from the variable
    setattr(p, f, row[key]) 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.