1. 程式人生 > >python文件備份與簡單操作

python文件備份與簡單操作

readlines file with open 10.10.4 with lines elif num 簡單操作

#!/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‘ + ‘\n‘
url2=‘server 10.10.4.xx‘+ ‘\n‘
# 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)

  

python文件備份與簡單操作