Hi I'm trying to write a small helper function to save an object to a csv under its own name.
I'm working with arrays of data and this is intended to be a workaround to help visualise the array easily to help with editing it.
The challenge I'm facing is that I'm unclear is how to get the function to look through the x
variable to the name of a
in the MWE below. what I'd like to be able to do is save it as a.csv
. getattr()
doesn't work so I'm stumped.
import random
import csv
def csvit(x):
f=open(name(x)+'.csv','wb'):
writer = csv.writer(f,quotechar='"', quoting=csv.QUOTE_ALL)
[writer.writerow(i) for i in x]
f.close()
a = []
for i in range(10):
t = [random.randint(0,1000) for r in range(10)]
a.append(t)
the name(x) isn't a working function and I don't know what to use in its place. I'm really looking for a function where fun(x)
yields ["a"]
for completeness the code that seems to work on the back of @PhilCooper 's answer below is
import csv
def csvit(x):
tmp = next(key for key,val in globals().items() if val == x and not key.startswith('_'))
f=open('/home/me/Desktop/csvs/'+tmp+'.csv','wb')
writer = csv.writer(f,quotechar='"', quoting=csv.QUOTE_ALL,dialect=csv.excel)
[writer.writerow(i) for i in x]
f.close()
Would welcome any comments or improvements on it.