0

I have a folder full of .txt files; I'd like to assign the data in the files to arrays (all of which happen to have length 6x9 in the example below, but obviously these dimensions are not so important); and I'd like the array names to be the ones given by the .txt file name.

I can do what seem to be the first necessary steps like ...

x=glob.glob('*.txt')
y=np.empty_like(x)
for i in range(len(x)):
    y[i]=x[i].rstrip('.txt')
z=np.empty((len(x),6,9))
for i in range(len(x)):
    z[i] = np.loadtxt(x[i], delimiter = ',')

... then I would like to do something like

for i in range(len(z)):
    y[i] = z[i]

but I get an error: ValueError: cannot set an array element with a sequence.

How can I get around this? I need the arrays to have names in order to resume analysis on them. Evaluating the arrays every time I want them takes too much time.

Any help is appreciated,

Thanks!

user1451632
  • 301
  • 1
  • 2
  • 10
  • 2
    Sounds like you want a dictionary. You "array name" would then simply be a dictionary key. – Gio Feb 12 '15 at 16:47
  • 1
    Please read [How can you dynamically create variables in Python via a while loop?](http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop) and [Keep data out of your variable names](http://nedbatchelder.com/blog/201112/keep_data_out_of_your_variable_names.html) on why this sounds like a bad idea. – martineau Feb 12 '15 at 16:48
  • What do you want each element of `y` to ultimately be? – martineau Feb 12 '15 at 17:02
  • I'd like to eventually forget about y. Instead, I'd like to have each name loaded via y to be assigned an array, such that each file name is a unique array. For example `yA.txt` would give me an array `yA` with values corresponding to those in `yA.txt`. If I was curious about all of my arrays, I could in principle look them up via `y` in this example, but that's not crucial to me. [This](http://stupidpythonideas.blogspot.com/2013/05/why-you-dont-want-to-dynamically-create.html) seems to do what I'm after, I think. – user1451632 Feb 12 '15 at 17:31
  • The problem with your current code is that you create `y` with `np.empty_like(x)` which gives it a one dimensional shape, then later you try to assign it multi-dimensional array elements. Seems like you could use `z[i]` which already has the data loaded from the corresponding file in it. One problem with creating an array named `yA` from the file's name, is how will your code know what variable name(s) to use to access the data in it? To do so would mean you'd be hardcoding the names of the files into your program, which could be a problem if they're ever changed. – martineau Feb 12 '15 at 18:12
  • Thanks for all the help. I think I will take this opportunity to get more comfortable with dictionaries... – user1451632 Feb 12 '15 at 19:09

0 Answers0