1

I'm looking to get a function to export Numpy arrays, but to use the name of the variable input to the function as the name of the exported file. Something like:

MyArray = [some numbers]

def export(Varb):
    return np.savetxt("%s.dat" %Varb.name, Varb)

export(MyArray)

that will output a file called 'MyArray.dat' filled with [some numbers]. I can't work out how to do the 'Varb.name' bit. Any suggestions?

I'm new to Python and programming so I hope there is something simple I've missed! Thanks.

Siyh
  • 1,747
  • 1
  • 17
  • 24

3 Answers3

1

You can't. Python objects don't know what named variables happen to be referencing them at any particular time. By the time the variable has been dereferenced and sent to the function, you don't know where it came from. Consider this bit of code:

map(export, myvarbs)

Here, the varbs were in some sort of container and didn't even have a named variable referencing them.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
1

I don't recommend such a code style, but you can do it this way:

import copy
myarray = range(4)
for k, v in iter(copy.copy(locals()).items()):
    if myarray == v:
        print k

This gives myarray as output. To do this in a function useful for exports use:

import copy
def export_with_name(arg):
    """ Export variable's string representation with it's name as filename """
    for k, v in iter(copy.copy(globals()).items()):
        if arg == v:
            with open(k, 'w') as handle:
                handle.writelines(repr(arg))

locals() and globals() both give dictionaries holding the variable names as keys and the variable values as values.

Use the function the following way:

some_data = list(range(4))
export_with_name(some_data)

gives a file called some_data with

[0, 1, 2, 3]

as content.

Tested and compatible with Python 2.7 and 3.3

sebix
  • 2,943
  • 2
  • 28
  • 43
  • Thanks @sebix, I'm really struggling to implement your suggestion, its seems to just output 'none'. What am I missing? – Siyh Dec 10 '14 at 14:45
  • I cannot reproduce your problem. I updated the answer for 3.3 compatibility and an usage example. Please post your code if the problem persists. – sebix Dec 10 '14 at 18:42
  • If I run the 2nd and 3rd blocks of code you've posted above I get the error: TypeError: object.__new__(listiterator) is not safe, use listiterator.__new__() – Siyh Dec 12 '14 at 14:30
  • @Siyh I rearranged the calls of `items()`, `copy()` and `iter()`, and it should work now finally for all versions. – sebix Dec 12 '14 at 19:43
0
import os
import inspect
import re

number_array = [8,3,90]

def varname(p):

       for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:

           m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
           if m:
               return m.group(1)

def export(arg):

    file_name = "%s.dat" % varname(arg)
    fd = open(file_name, "w")
    fd.writelines(str(arg))
    fd.close()

export(number_array)

Refer How can you print a variable name in python? to get more details about def varname()

Community
  • 1
  • 1
hariK
  • 2,722
  • 13
  • 18