利用python合并两个文件

1格式如下

在做利用zabbix的api来批量添加主机的时候,需要处理ip和hostname,在借用别人写的py程序的基础上,自己有改装了以下脚本,为自己使用。需要时ip和hostname为一个统一格式。

$ cat ip.txt 
1.1.1.1
2.2.2.2
3.3.3.3
4.4.4.4
$ cat hostname.txt
tx-1
tx-2
tx-3
tx-4

最后需要合并为如下格式

1 tx-1,1.1.1.1
2 tx-2,2.2.2.2
3 tx-3,3.3.3.3
4 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 ip 12 #print hostname 13 #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

posted @ 2016-12-03 21:10  Dicky_Zhang  阅读(4902)  评论(0编辑  收藏  举报