如何将逗号插入

问题描述 投票:0回答:1

我在目录中有一堆文本文件,需要替换其中的文本。每行看起来像这样:

B6 0x040A43

B17 0x6C00C8

我需要:

  1. 用“ 1,28”替换第一部分
  2. 删除空格,它是一个'\ t'空白
  3. 删除十六进制标识符'0x'
  4. 在接下来的两个字符后添加逗号

所以结果应如下所示:

1,28,04,0A43

1,28,6C,00C8

我仍在学习python和regex,经过数小时的学习,这是我到目前为止编写的内容:

for filename in glob.glob(os.path.join(directory, '*.txt')):
    with open(filename, "r") as f:
        lines = f.read().splitlines()
        for line in lines:
            line = re.sub(r'B\d{1,}[\s+]0x','1,28,', line)
            print(line)

这将打印出'1,28,040A43',因此除最后一个逗号外,其他所有内容均会显示。

如何将逗号插入字符串?这是替换文件中文本的最佳方法还是应该以其他方式访问它?

非常感谢您提供任何帮助。

谢谢。

python regex file overwrite
1个回答
0
投票
import glob
import os
import re
directory = 'test'
for filename in glob.glob(os.path.join(directory, '*.txt')):
    with open(filename, "r") as f:
        lines = f.read().splitlines()
        for line in lines:
            line = re.sub(r'B\d{1,}[\s+]0x','1,28,', line)
            line = line[:7] + ',' + line[7:]
            print(line)


输出

1,28,04,0A431,28,6C,00C8

© www.soinside.com 2019 - 2024. All rights reserved.