python - 在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
如果我能得到一些帮助或功能来进行数据处理,那么我从逻辑开始会更容易。
解决方案
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
推荐阅读
- android - 在 Android 启动画面的层列表中定位图像
- c++ - DirectXTK 在“SetWindow(HWND hwnd)”的“鼠标”中没有成员
- groovy - 如果在 Groovy 中返回,JaCoCo 会丢失行
- python - 无法在模板视图中使用“categories.products .all”访问数据。带有外键的 Django 模型
- python - 比较两个数据帧并返回不同的值
- wpf - 绑定到 ObservableCollection 的 DataGrid 在值更改后不会立即更新
- npm - 如何单击使用 webdriver io 移动的元素?
- jenkins - 并行运行单个 jenkins 作业
- linux - 如何在 Unix 中的两个日期范围之间 grep 日志
- node.js - 可以在 node js(Express js)中使用 Firebase ML Kit 吗?