首页 > 解决方案 > 在python中组合txt文件中的行

问题描述

我的文本文件中有以下数据。

26 #denotes the number of lines to process
01 #LSB1
FF #MSB1
02 #LSB2
FE #MSB2
03 #LSB1
AA #MSB1
04 #LSB2
AE #MSB2
01 
FF
02
FE
01
AA
02
AE
01
FF
02
FE
00 #exclude these lines
01 #exclude these lines
02 #exclude these lines
03 #exclude these lines
04 #exclude these lines
05 #exclude these lines
18 #denotes the number of lines to process
01
FF
02
FE

.... 等等

第一行表示文件中要处理的行数。在这种情况下,它是 26。所以我必须将以下 20 行数据处理成如下所示的模式

00000026
FE02FF01 
AE04AA03
FE02FF01
AE02AA01
FE02FF01
00000018

#Counter = Line1 - 6

这里第一行用尾随零填充,使其成为 32 位数据。下一行是 (MSB2 + LSB2 + MSB1 + LSB1)。这将在文本文件中的接下来的 20 行中完成。其余 6 行将被排除。然后再次检查下一行的计数器。在这种情况下,它将是 18-6=12.. 所以处理接下来的 12 行并跳过以下 6 行。

我编写了以下代码以将数据保存在输出 txt 文件中。但我不知道如何处理模式部分。

with open(filename) as fp:
            memArray = [line.strip() for line in fp]
            mem_file.write(memArray[0].zfill(8)+"\n")
            count = int(memArray[0]) - 6

如果我能得到一些帮助或功能来进行数据处理,那么我从逻辑开始会更容易。

标签: python

解决方案


with open(filename) as fp:
    memArray = [str(line.strip()) for line in fp]


    index = 0
    while index < len(memArray):
        count = memArray[index]
        print(count.zfill(8))
        index += 1

        data_count = int(count) - 6
        for i in range(int(data_count / 4)):

            print("".join(memArray[(index + 3):(index-1):-1]))
            index += 4
        index += 6

推荐阅读