user1551817
user1551817

Reputation: 7451

adding columns to a text file

I have a data file that is just one column. I want to add 2 columns to the left and 2 columns to the right of it.

I thought that an easy way to do this would be be using numpy arrays, and here is what I tried:

z = np.loadtxt('data_file.dat')

new = np.zeros((z.shape[0],5))

for i in range(z.shape[0]):
    new[i,0] = 'w040_0731.QR'
    new[i,1] = 1666.000
    new[i,2] = z[i]
    new[i,3] = 0.10000
    new[i,4] = 7

z.close()

But it didn't work - I think because a numpy array is not designed to have a mixture of numbers and strings? I got the error message:

could not convert string to float: w040_0731.QR

Could someone please suggest the most efficient way to add 2 columns to the left and 2 columns to the right of a text file that I have?

Upvotes: 3

Views: 7637

Answers (1)

Hans Then
Hans Then

Reputation: 11322

This should do it, assuming your columns are space separated, but it does not use numpy:

with open('data_file.dat') as in_file, open('output', 'w') as out_file:
    for line in in_file:
         data = float(line.strip())
         print >> outfile "'w040_0731.QR'", '1666.000', data, '0.10000', '7' 

Upvotes: 4

Related Questions