file1.txt
neighbors:
- { neighbor: 192.168.3.1,remote-as: 200,group: Google }
- { neighbor: 192.168.4.1,remote-as: 300,group: FOX }
- { neighbor: 192.168.15.1,remote-as: 400,group: TAX }
- { neighbor: 192.168.16.1,remote-as: 500,group: TSL }
- { neighbor: 192.168.5.1,remote-as: 400,group: TAM }
我想 ot 制作一个文件1.txt ( 没有第一行 en (-{},:,(
neighbor 192.168.3.1 remote-as 200
neighbor 192.168.4.1 remote-as 300
neighbor 192.168.15.1 remote-as 400
neighbor 192.168.16.1 remote-as 500
neighbor 192.168.5.1 remote-as 400
该文件采用 YAML 格式。通常,您会使用扩展名而不是.txt
指定.yml
但这不会影响文件内容。与其使用正则表达式之类的东西进行解析,不如以 YAML 格式读取并在所需的输出中写回。有关更多详细信息,请参阅 PyYAML 的文档。
import yaml
with open('test.txt') as infile:
data = yaml.load(infile)
with open('test_out.txt', 'w') as outfile:
for neighbor in data['neighbors']:
outfile.write('neighbor {} remote-as {}n'.format(neighbor['neighbor'],
neighbor['remote-as']))
请注意,字典在 python 3.6 中才开始排序,并且只保证在 3.7+ 中排序,因此对于早期版本的 Python,不能保证您将获得确切的所需输出。
您可以通过在要写出的字符串中指定子字典键来缓解此问题。