将列添加到文本文件 [英] adding columns to a text file

查看:72
本文介绍了将列添加到文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个仅一列的数据文件.我想在左侧添加2列,在右侧添加2列.

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.

我认为一种简单的方法是使用numpy数组,这是我尝试的方法:

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()

但是它没有用-我认为是因为numpy数组不是设计为将数字和字符串混合在一起的?我收到错误消息:

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

有人可以建议一种最有效的方法,在我拥有的文本文件的左侧添加2列,在右侧添加2列吗?

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?

推荐答案

如果您的列之间用空格隔开,则应该这样做,但是它不使用numpy:

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' 

这篇关于将列添加到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆