Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How save a array to text file in python?

I have a array of this type:

xyz = [['nameserver','panel'], ['nameserver','panel']]

How can I save this to an abc.txt file in this format:

nameserver panel
nameserver panel

I tried this using, on iterating over each row:

np.savetxt("some_i.txt",xyz[i],delimiter=',');

It's showing this error:

TypeError: Mismatch between array dtype ('<U11') and format specifier 
('%.18e')
like image 629
sarpit23 Avatar asked Aug 15 '18 14:08

sarpit23


People also ask

How do I save a Numpy array to a text file in Python?

Let us see how to save a numpy array to a text file. Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function.

How do you save data to a text file in Python?

To write to a text file in Python, you follow these steps: First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.


2 Answers

This is a possible solution:

data = [['nameservers','panel'], ['nameservers','panel']]

with open("output.txt", "w") as txt_file:
    for line in data:
        txt_file.write(" ".join(line) + "\n") # works with any number of elements in a line
like image 66
ybl Avatar answered Sep 27 '22 23:09

ybl


Probably the simplest method is to use the json module, and convert the array to list in one step:

import json

with open('output.txt', 'w') as filehandle:
json.dump(array.toList(), filehandle)

Using the json format allows interoperability between many different systems.

like image 37
Agile Bean Avatar answered Sep 28 '22 00:09

Agile Bean