Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write long list to file all on one line

In Python the following code:

data = [np.array([[1,2,3],[4,5,6]]),[7]]
with open('A:\\examplefile.txt', 'w', newline='') as file:
      file.write(str([item for item in data]))

writes the nested list to multiple lines in the file, thus:

[array([[1, 2, 3],
       [4, 5, 6]]), [7]]

How might I write the entire list onto on line in the file? e.g.:

[array([[1,2,3],[4,5,6]]),[7]]
like image 586
quantllama Avatar asked Oct 31 '25 11:10

quantllama


1 Answers

Numpy formats ndarray output by using '\n' and whitespaces such that it is readable in form of a matrix. So replacing '\n' and whitespace will do the trick.

Try this,

data = [np.array([[1,2,3],[4,5,6]]),[7]]
with open('A:\\examplefile.txt', 'w', newline='') as file:
    file.write(str(data).replace('\n','').replace(' ',''))
like image 91
Akash Karnatak Avatar answered Nov 02 '25 01:11

Akash Karnatak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!