如何在此文件中的每 4 个元素之后将输出附加到 txt 文件 [英] How to append an output to a txt file after every 4th element in this file

查看:20
本文介绍了如何在此文件中的每 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 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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