python练习:替换文件内容

转自:http://blog.csdn.net/hometohw/article/details/7483404

1.替换

import re  
file_name='new  4.txt'  
fp=open(file_name,'r')  
alllines=fp.readlines()  
fp.close()  
fp=open(file_name,'w')  
for eachline in alllines:  
    a=re.sub('<host_ip>0.0.0.0</host_ip>','<host_ip>1.1.1.1</host_ip>',eachline)  
    fp.writelines(a)  
fp.close()  

2.单行替换

import re  
import os  
filelist=['new  4.txt','new  5.txt']  
workdir=input('please input WORK_HOME : ')  
os.chdir(workdir)  
ipold=input('Please input the old ip : ')  
ipnew=input('Please input the new ip : ')  
for filename in filelist:  
    fp=open(filename,'r')  
    alllines=fp.read()  
    fp.close()  
    fp=open(filename,'w')  
    fp.writelines(re.sub(ipold,ipnew,alllines))  
    fp.close()  

3.多行替换

import re  
import os  
filelist=['new  4.txt','new  5.txt']  
workdir=input('please input WORK_HOME : ')  
os.chdir(workdir)  
ipold=input('Please input the old ip : ')  
ipnew=input('Please input the new ip : ')  
for filename in filelist:  
    fp=open(filename,'r')  
    alllines=fp.readlines()  
    fp.close()  
    fp=open(filename,'w')  
    fp.truncate()  
    for eachline in alllines:  
        fp.writelines(re.sub(ipold,ipnew,eachline))  
    fp.close()  

4.能用的

import re  
import os  
filelist=['new  4.txt','new  5.txt']  
workdir=input('请输入工作目录,当前目录请直接按回车 : ')  
if workdir!='':  
    os.chdir(workdir)  
oldip=input('请输入原来IP : ')  
newip=input('请输入当前IP : ')  
for filename in filelist:  
    fp=open(filename,'r')  
    alllines=fp.read()  
    fp.close()  
    fp=open(filename,'w')  
    fp.writelines(re.sub(oldip,newip,alllines))  
    fp.close()