本文介绍了如何在此文件的第4个元素之后将输出附加到txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很抱歉,但是我是Python的新手,并且我有包含此类数据的文件
I am sorry but I am new in Python and I have file which have data like this
x1 y1 z1 w1 x2 y2 z2 w2 .. xn yn zn wn
我想在每w之后附加一些数字.因此基本上是在txt文件中的第4个元素之后.
I would like to append some number after every w. so basically after every 4th element in the txt file.
请问有什么建议吗?非常感谢
Is there any recommendations please?Thanks a lot
更新:txt文件中的数据均为字符串.我能够将它们转换
Update : The data which is in the txt file are all strings.I was able to convert them
f = open("test.txt","r+").readlines()
for line in f:
tmp = line.strip().split(",")
values = [float(v) for v in tmp]
my_data = [1 1 2 23 1]
a = np.insert(a,slice(0,None,4),my_data)
np.savetxt(filename, a)
附加部分仍无法正常工作.
The appending part didn't work still.
推荐答案
您必须首先将此文件读入数组,插入项目并将其保存回去(假设文本文件的名称为filename
):
You have to first read this file into an array, insert items and save it back (assuming your text file's name is filename
):
import numpy as np
your_number = #number you want to insert OR a list of numbers you want to insert consecutively in those locations
a = numpy.loadtxt(filename)
a = np.insert(a,slice(0,None,4),your_number)
np.savetxt(filename, a)
示例:
a = np.zeros(10)
#[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
l = [1,2,3]
a = np.insert(a,slice(0,None,4),l)
输出
[1. 0. 0. 0. 0. 2. 0. 0. 0. 0. 3. 0. 0.]
这篇关于如何在此文件的第4个元素之后将输出附加到txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!