首页 > 解决方案 > 使用python3修改数据及其格式

问题描述

来自 file.txt 的输入

ip route 10.8.125.144/28 10.0.59.5 description Sunny_House_HLR1_SIG

file2.txt 中需要的输出

static-route-entry 10.8.125.144/28 next-hop 10.0.59.5 description "Sunny_House_HLR1_SIG" no shutdown exit exit

谁能告诉我该怎么做?

标签: python-3.x

解决方案


文件输入/输出

您可以使用以下语句从文件中读取:

in_file = open('file.txt', 'r')
data = in_file.read()
in_file.close()

和写:

out_file = open('file2.txt', 'w')
out_file.write(data)
out_file.close()

我建议查看有关读取/写入文件的官方 python 文档部分

数据处理

至于解析、理解和格式化您收到的数据,这有点复杂。这取决于您希望获得哪些数据,您希望如何操作它等等。

对于您专门给出的示例(并且是该示例),这是对数据的非常直接的解析:

# Read data from file.txt

# Split the string based on spaces,
# discarding the entries you don't use 
# by labeling them as underscores
_, _, sre, nh, _, desc = data.split(' ') 

# Insert the extracted values into a
# multi-line formatted string
final_output = f"""\ 
static-route-entry {sre}
    next-hop {nh}
        description {desc}
    exit
exit
"""

# Write final_output to file2.txt

如果您期望在 file.txt 中的数据以任何方式发生变化,您将不得不编写一个更复杂的解析算法,但这应该会给您一个开始。


推荐阅读