#!/usr/bin/python # -*- coding: utf-8 -*- # data:2018/8/30 # user:fei import sys import random num = random.sample(range(5,10),1)[0] url1='server 10.10.4.yy' + ' ' url2='server 10.10.4.xx'+ ' ' # url = url1 + url2 souse1 = '1xx' souse2 = '1yy' oldfile_url = '/etc/ntp.conf' newfile_url = '/home/work/opdir/ntp.conf-bak' src = file(oldfile_url,'r') dst = file(newfile_url,'w') dst.write(src.read()) src.close() dst.close() with open(newfile_url,"r") as f: lines = f.readlines() #写的方式打开文件 with open(oldfile_url,"w+") as f_w: for line in lines: if souse1 in line: line = url1 elif souse2 in line: line = url2 f_w.write(line)