利用python合并兩個檔案

來源:互聯網
上載者:User

標籤:檔案   添加   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合并兩個檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.