Home > Net >  export list of arrays to txt file in python
export list of arrays to txt file in python

Time:09-07

I have a list of arrays that I want to export as a txt file.

x = [[np.array([0, 0, 0]), np.array([1,2,2])], [np.array([0, 0, 0]), np.array([4,5,6])]]

desired output shape:

(0,0,0),(1,2,2)
(0,0,0),(4,5,6)

I tried to use all the following methods but I didn't get the same thing I need.

# Trial1
np.savetxt(full_path, x, delimiter = ',')

Error: Expected 1D or 2D array, got 3D array instead

# Trial2
np.save(full_path, x, allow_pickle=True)
# Not possible, can't handle the extension from pickle

..

# Trial3
df = pd.DataFrame(x)
print(df.to_csv(index=False, header=False))

Output close but not what I'm look for

[0 0 0],[1 2 2]

[0 0 0],[4 5 6]

Any other ideas?

CodePudding user response:

you could convert the numpy arrays to tuples, because their string representation uses parentheses instead of brackets.

arrays = [[np.array([0, 0, 0]), np.array([1,2,2])], [np.array([0, 0, 0]), np.array([4,5,6])]]

linesToFile = [str(tuple(x[0]))   ','   str(tuple(x[1])) for x in arrays]

with open(full_path, "w") as f:
    for line in linesToFile:
        f.write(line   "\n")
  • Related