0

I'm trying to generate variables automatically and put them in a csv file, to do so, I'm using the code bellow, which works fine:

#val is the number of points I want to generate and store them in a list:
val = 3 
list_of_points = []

#Generate 3 points automatically:
g = globals()
for i in range(1, val+1):
    g['p{0}'.format(i) ] = str('p{0}'.format(i))
    list_of_points.append(g['p{0}'.format(i)])

My problem is that I want to put them inside the "for()" loop and also the dictionnary bellow it, I can't think of any way to do this, there is my code bellow:

writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
for (p1,p2,p3) in zip(list_p1,list_p2,list_p3):
    writer.writerow({'p1': p1, 'p2': p2,'p3': p3})

Any idea how can I achieve this ? thanks.

alioua walid
  • 247
  • 3
  • 19
  • Modifying the globals object seems... scary to me. Why exactly are you doing that? What is your desired result here? Do you just want to create a csv containing some special content? – Lydia van Dyke Apr 07 '20 at 23:38
  • @LydiavanDyke I'm trying to generate points and list of points to store them dynamically ( the code is longer, I just took the part that's not working), I'm importing data from excel files, some excel files have 10 points, others more than that, the user need to choose how many points he want to get in the beginning of the script – alioua walid Apr 07 '20 at 23:43
  • 1
    Ok then. For your task you should not need the `globals` object. Forget that you ever heard about it, trust me :) Have a look at the proposed solution https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables. You should solve your problem with a normal dictionary (or maybe even a list). – Lydia van Dyke Apr 07 '20 at 23:47
  • @LydiavanDyke Why do you consider this approach wrong ? most answers in the link are using it – alioua walid Apr 07 '20 at 23:56
  • That may be. But have a look at the scores! Accepted answer 285 (it does not use globals). Most of the other answers are in the order of 10 at most. And if the OP _wants_ to use globals, many answer will grant this wish. When you are too focused on fixing a problem on your path, you may very easy overlook that you were on the wrong path all along. – Lydia van Dyke Apr 08 '20 at 00:04

0 Answers0