Dax Feliz
Dax Feliz

Reputation: 12899

Python: Turning arrays into text files

I have this processed data in the format of:

x = [1,2,3,4,5,6]

and so on. How could I take this list and turn it into a .txt file?

Upvotes: 0

Views: 128

Answers (3)

mfjones
mfjones

Reputation: 739

In python, you can write to a file using the write command. write() writes the contents of a string into the buffer. Don't forget to close the file as well using the close() function.

data = [1,2,3,4,5,6]

out = open("output.txt", "w")

for i in data:
    out.write(str(i) + "\n")

out.close()

Upvotes: 0

mawueth
mawueth

Reputation: 2806

with open(r'C:\txtfile\exported_array.txt', 'w+') as txt_export:
    for i in x: txt_export.writelines(str(i))

will save 123456 into txt

with open(r'C:\txtfile\exported_array.txt', 'w+') as txt_export:
    for i in x: txt_export.writelines(str(i)+',')

will save 1,2,3,4,5,6, into txt

with open(r'C:\txtfile\exported_array.txt', 'w+') as txt_export:
    for i in x: txt_export.writelines(str(i)+'\n')

will save

1
2
3
4
5
6

into txt

Upvotes: 2

nneonneo
nneonneo

Reputation: 179422

Python 2.7, to produce one number per line:

with open('list.txt', 'w') as f:
    print >> f, '\n'.join(str(xi) for xi in x)

You can use any other join string, like ',' to produce the numbers comma-separated all on one line.

Upvotes: 1

Related Questions