Adam Merckx
Adam Merckx

Reputation: 1244

Get Data Horizontally in a text file

I have written my script in Python and here is the code:

output=[]
i=0
for i in range(0,3089879):
   norm = str(data_normE[i,0])
   output.append(normE_string)

So, the output is like this:

0.01
0.023
0.456
0.9834
0.23

... so on till 3089879th row.

I would like to write as follows:

0.01    0.023    0.456    0.9834    0.23        (till 3089879 columns).

What could I change in my code? I am writing the contents in a text file. I have many files of this sort, so though I know how to use excel it is back-breaking work to do it for hundred thousand files. Can anyone please help??

Upvotes: 0

Views: 1505

Answers (1)

elzell
elzell

Reputation: 2306

There are two ways:

You could either open a text file and write the result in each iteration of the for loop directly into the file with write:

with open(filename, 'w') as file:
    for i in range(3089879):
        norm = str(data_normE[i,0])
        file.write(norm + ' ')

file.write does not append a newline.

Or to use your array with all results as strings after the for loop you can also join these with

' '.join(output)

to get a huge string which you can then write into the file. I'd propose the first solution because it is more (memory) efficient.

Upvotes: 2

Related Questions