将列添加到文本文件
问题内容:
我有一个仅一列的数据文件。我想在左侧添加2列,在右侧添加2列。
我认为一种简单的方法是使用numpy数组,这是我尝试的方法:
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数组的设计目的不是将数字和字符串混合在一起?我收到错误消息:
could not convert string to float: w040_0731.QR
有人可以建议一种最有效的方法,在我拥有的文本文件的左侧添加2列,在右侧添加2列吗?
问题答案:
假设您的列之间用空格分隔,则应该这样做,但是它不使用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'