標籤:檔案 添加 writer import 利用 指令碼 color span 統一
1格式如下
在做利用zabbix的api來大量新增主機的時候,需要處理ip和hostname,在借用別人寫的py程式的基礎上,自己有改裝了以下指令碼,為自己使用。需要時ip和hostname為一個統一格式。
$ cat ip.txt 1.1.1.12.2.2.23.3.3.34.4.4.4
$ cat hostname.txttx-1tx-2tx-3tx-4
最後需要合并為如下格式
1 tx-1,1.1.1.12 tx-2,2.2.2.23 tx-3,3.3.3.34 tx-4,4.4.4.4
上指令碼1:
1 cat ip_hostname.py 2 3 #!/usr/bin/env python 4 #_*_coding:utf-8_*_ 5 6 import itertools 7 8 with open("ip.txt") as f: 9 txt1=[r.rstrip("\n") for r in f.readlines()]10 with open("hostname.txt") as f:11 txt2=[r.rstrip("\n") for r in f.readlines()]12 13 14 result=itertools.izip_longest(txt1,txt2,fillvalue=‘ ‘)15 #[print(r) for r in result]16 17 with open("result.txt","w+") as f:18 [f.write(‘,‘.join(r)+"\n") for r in result]
或者使用參數:(簡練)
1 cat ip-hostname.py
#!/usr/bin/env python 2 # coding: utf-8 3 4 import sys 5 import csv 6 file1=sys.argv[1] 7 file2=sys.argv[2] 8 9 ip=open(file1,‘r‘).readline().strip()10 hostname=open(file2,‘r‘).readline().strip()11 #print ip12 #print hostname13 #print open(file1,‘r‘).readall()14 15 name=ip+‘,‘+hostname+‘\n‘16 17 18 with open(‘names.txt‘, ‘w‘) as file3:19 for i in file1 :20 writer = file3.write(name)
運行:
python ip-hostname.py ip.txt hostname.txt
利用python合并兩個檔案