Python文本文件格式

2024-06-03 05:24:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用Python进行一些文本文件格式化。我有串行口的数据,都在一个文件中,一个字符接一个字符。我知道如何查找和替换文件中的文本,但我需要执行以下操作:

  1. 查找string int file,(文件中会有很多字符串,不知道有多少)
  2. Set在此字符串后添加空格(或其他字符)。我找不到如何操作文件中的光标位置。在

如何获取文件中字符串的位置?在

例如,文件中的数据如下:

(这基本上是来自串行端口的十六进制数据,但在保存到文件之前转换为字符串。所以在文件中这些数据只是文本。里面也可能有“你好世界”之类的东西。在

如何转换:

00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C00000001030001000151CD0203000100015D1E00000406001000545E5C

我想查找从“0103”开始的部件(它是设备地址),然后在“0103”之前加上“\n”,然后在下面四个字符之后再加上一个空格和文本“this was device number one”:

到这个地方:

000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C000000 0103"this was device number one"0001000151CD0203000100015D1E00000406001000545E5C

整个程序用于监听Modbus RTU线路,记录日志。在


Tags: 文件数据字符串文本numberstringdevicethis
1条回答
网友
1楼 · 发布于 2024-06-03 05:24:13

def adjustString(deviceNumber):
    newData = str.replace(data, deviceNumber, '\n' + deviceNumber + ' this was device number one')
    return newData

with open('data.txt', 'r') as myfile:
    data=myfile.read().replace('\n', '')

output = adjustString('0103')



然后可以根据需要将新字符串写入文件。在

^{pr2}$

相关问题 更多 >