How to append an output to a txt file after every 4th element in this file

北城以北 提交于 2020-07-23 06:31:06

问题


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

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

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.


回答1:


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)

Example:

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)

output

[1. 0. 0. 0. 0. 2. 0. 0. 0. 0. 3. 0. 0.]



回答2:


Quick and dirty if you aren't entirely sure that the w elements are there like you say they might be. "data" is the file you're reading in. I assumed that your data is read in where every line is like the format you said. We split the line on the default whitespace and get array(s) representations of the line. We then iterate through each array and replace the old word with the new word wherever we find a match.

Note: Strings are immutable so it's best to use a way like enumerate to actually replace the word in the array with the new word.

  with open("data", "r") as f:
       tot_lines = [line.split() for line in f]
       for line in tot_lines:
           for key, word in enumerate(line):
               if word[0] == "w":
                   line[key] = word + str(9999)
       print(tot_lines)



回答3:


Your problem is your question. First, you say:

I have file which have data like this

x1 y1 z1 w1 x2 y2 z2 w2 .. xn yn zn wn

But in your code you do: split(",") So your data really looks like:

x1,y1,z1,w1,x2,y2,z2,w2,...,xn,yn,zn,wn

And you want your data to look like:

x1,y1,z1,w1,v1,x2,y2,z2,w2,v2,...,xn,yn,zn,wn,vn

Where the vn values come from:

my_data = [1 1 2 23 1]

Which we note isn't valid Python syntax so your posted code doesn't actually run. The small amount of data also seems odd for multiline input but let's go with it. We're looking at five sets of four data items or 20 numbers per line as input. For example, if we had a five line file, we'd see something like:

> cat test.txt
47,18,96,31,48,33,64,21,92,35,78,62,56,23,25,47,35,9,15,9
34,38,64,72,66,69,18,57,92,3,58,17,96,19,53,63,97,86,24,41
2,52,22,59,27,58,82,45,90,24,26,51,47,43,17,14,8,54,4,58
13,99,78,61,99,8,65,10,62,56,91,66,45,18,41,50,75,95,62,80
48,30,18,46,93,82,25,15,93,1,45,88,22,97,54,47,54,64,16,91
>

The appending part didn't work still.

That's fine as appending really isn't the right way to go here. To insert our new data, using basic Python sans numpy, I'd do something like:

my_data = [1, 1, 2, 23, 1]

with open("test.txt") as input_file:
    with open("revised.txt", 'w') as output_file:

        for line in input_file:
            array = line.rstrip().split(',')

            for index, datum in enumerate(my_data, 1):
                array.insert(index * 5 - 1, str(datum))

            print(','.join(array), file=output_file)

(The index math index * 5 - 1 is tricky as the array indexes change as we add each new item.) With the resulting output:

> cat revised.txt 
47,18,96,31,1,48,33,64,21,1,92,35,78,62,2,56,23,25,47,23,35,9,15,9,1
34,38,64,72,1,66,69,18,57,1,92,3,58,17,2,96,19,53,63,23,97,86,24,41,1
2,52,22,59,1,27,58,82,45,1,90,24,26,51,2,47,43,17,14,23,8,54,4,58,1
13,99,78,61,1,99,8,65,10,1,62,56,91,66,2,45,18,41,50,23,75,95,62,80,1
48,30,18,46,1,93,82,25,15,1,93,1,45,88,2,22,97,54,47,23,54,64,16,91,1
>

If this isn't what you're trying to do, please rewrite your question clarifying your file format, clearly stating your goals and providing good examples.



来源:https://stackoverflow.com/questions/62821021/how-to-append-an-output-to-a-txt-file-after-every-4th-element-in-this-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!