zoukankan      html  css  js  c++  java
  • 利用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("
    ") for r in f.readlines()]
    10 with open("hostname.txt") as f:
    11     txt2=[r.rstrip("
    ") 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)+"
    ") 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+' ' 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

  • 相关阅读:
    前端笔记-jquery
    git的使用
    前端笔记-bom
    微信小程序没找到构建npm或者没找到node_modules目录
    微信小程序判断 wx:if wx:else
    微信小程序提示云函数部署不成功
    cmd如何进入文件夹
    微信小程序view居中
    vue页面跳转兄弟组件传值
    vue全局变量apiurl
  • 原文地址:https://www.cnblogs.com/Dicky-Zhang/p/6129649.html
Copyright © 2011-2022 走看看