简体   繁体   English

如何在此文件中的每 4 个元素之后将 append 和 output 转换为 txt 文件

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

I am sorry but I am new in Python and I have file which have data like this我很抱歉,但我是 Python 的新手,我有文件包含这样的数据

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

I would like to append some number after every w.我想在每个 w 之后 append 一些数字。 so basically after every 4th element in the txt file.所以基本上在txt文件中的每4个元素之后。

Is there any recommendations please?请问有什么建议吗? Thanks a lot非常感谢

Update: The data which is in the txt file are all strings.更新:txt文件中的数据都是字符串。 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.附加部分仍然不起作用。

You have to first read this file into an array, insert items and save it back (assuming your text file's name is filename ):您必须首先将此文件读入数组,插入项目并将其保存回来(假设您的文本文件的名称是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 output

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

Quick and dirty if you aren't entirely sure that the w elements are there like you say they might be.如果您不完全确定 w 元素是否像您说的那样存在,那么快速而肮脏。 "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.注意:字符串是不可变的,因此最好使用 enumerate 之类的方式将数组中的单词实际替换为新单词。

  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)

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:但是在你的代码中你这样做: split(",")所以你的数据看起来像:

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: vn值的来源:

my_data = [1 1 2 23 1]

Which we note isn't valid Python syntax so your posted code doesn't actually run.我们注意到这不是有效的 Python 语法,因此您发布的代码实际上并没有运行。 The small amount of data also seems odd for multiline input but let's go with it.对于多行输入,少量数据似乎也很奇怪,但让我们用它 go 吧。 We're looking at five sets of four data items or 20 numbers per line as input.我们正在查看五组四个数据项或每行 20 个数字作为输入。 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.没关系,因为在此处附加 go 确实不是正确的方法。 To insert our new data, using basic Python sans numpy, I'd do something like:要插入我们的新数据,使用基本的 Python sans numpy,我会这样做:

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: (索引数学index * 5 - 1很棘手,因为随着我们添加每个新项目,数组索引会发生变化。)使用生成的 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.如果这不是您想要做的,请重写您的问题,澄清您的文件格式,明确说明您的目标并提供好的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM