python - 读取文件做一定的工作并将结果追加写入另一个文件

 
#coding=utf-8
import requests
import traceback
import argparse

parser = argparse.ArgumentParser()

parser.add_argument("-s", help="src_path_read_file", )
parser.add_argument("-d", help="dst_path_write_file", )

args = parser.parse_args()

src_path_file = args.s
dst_path_file = args.d
print '读取目录:',src_path_file
print '写入目录:',dst_path_file


# src_path = '/mnt/test_interface_03/test/ip01.txt'
src_path = src_path_file
# filename = '/mnt/test_interface_03/test/write_data.txt'
filename = dst_path_file

def get_data(inputIP):
    headers = {
        "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Mobile Safari/537.36"}
    url = "http://tooly.1x1.ooo/index.php?ip=" + inputIP
    r = requests.get(url, params=inputIP, headers=headers)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    return r.text
    # print 'r.text = ',r.text


# inputIP = raw_input("Enter You Check IP Address : ")
# html = get_data(inputIP)
try:
    with open(src_path, 'r') as f:
        a = f.read()
        ip_list = [i for i in a.splitlines() if i != '']

    print '需要查询的IP总数是:%d\n' % len(ip_list)
    k = 1
    for ip in ip_list:
        print '正在查询第 %d 个IP:%s' % (k, ip)
        # print '查询的ip是:%s' % ip #
        html = get_data(ip).encode('utf-8')
        print 'html = ',html #
        print '正在写入第 %d 个IP的查询结果!' % k
        with open(filename, 'aw') as f:  # 如果filename不存在会自动创建, 'w'表示写数据,写之前会清空文件中的原有数据!
            f.write('['+str(k)+']'+':'+ip+':'+html+'\n\n')
        print '第 %d 个IP的查询结果写入完毕!\n' % k
        k += 1
    print '查询完毕!。。。。。。。。。\n\n\n'
except Exception as e:
    traceback.print_exc()




可传入参数:
      -s指定读取目录
      -d指定写入目录
例如: python test.py -s 'src_fileName.txt' -d 'dst_fileName.txt'
注:运行环境python2.7




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值