简体   繁体   中英

combining lines in a txt file in python

I have the following data in my text file.

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

.... and so on

The first line denotes the number of lines to process in the file. In this case it is 26. So i have to process the following 20 lines of data into a pattern shown below

00000026
FE02FF01 
AE04AA03
FE02FF01
AE02AA01
FE02FF01
00000018

#Counter = Line1 - 6

Here the first line is filled with trailing zeroes to make it a 32bit data. The next line is (MSB2 + LSB2 + MSB1 + LSB1).This to be done for the next 20 lines in the text file. Remaining 6 lines are to be excluded. Then again check the counter from the next line. In this case it will be 18-6=12.. so process the next 12 lines and skip the following 6 lines.

I have written the following code to save the data in a output txt file. But i have no idea how to process the pattern part.

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

If i could get some help or functions to do the data processing it would be easier for me to start with the logic.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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