Merge two files with Python

Source: Internet
Author: User

1 format as follows

In the use of Zabbix API to bulk add the host, you need to deal with IP and hostname, on the basis of borrowing others to write the PY program, they have modified the following script for their own use. IP and hostname are a unified format when needed.

1.1. 1.1 2.2. 2.2 3.3. 3.3 4.4. 4.4
$ cat Hostname.txttx-1TX-2TX-3TX-4

Finally, you need to merge into the following format

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

On script 1:

1 Cat ip_hostname.py2 3#!/usr/bin/env python4#_ *_coding:utf-8_*_5 6 Import Itertools7 8With open ("Ip.txt") asF:9Txt1=[r.rstrip ("\ n") forRinchf.readlines ()]TenWith open ("Hostname.txt") asF: OneTxt2=[r.rstrip ("\ n") forRinchf.readlines ()] A  -  -Result=itertools.izip_longest (txt1,txt2,fillvalue=' ') the#[print (R) forRinchresult] -  -With open ("Result.txt","w+") asF: -[F.write (','. Join (R) +"\ n") forRinchResult

or Use parameters: (concise)

1Cat ip-hostname.py
#!/usr/bin/env python2# coding:utf-83 4 Import SYS5 Import CSV6file1=sys.argv[1]7file2=sys.argv[2]8 9Ip=open (File1,'R'). ReadLine (). Strip ()TenHostname=open (File2,'R'). ReadLine (). Strip () One #print IP A #print hostname -#print Open (File1,'R'). ReadAll () - thename=ip+','+hostname+'\ n' - - -With open ('Names.txt','W') asFile3: + forIinchfile1: -writer = File3.write (name)

Run:

Python ip-hostname.py ip.txt Hostname.txt

Merge two files with Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.