码迷,mamicode.com
首页 > 其他好文 > 详细

saltstack文件模块的replace操作简化

时间:2016-09-18 11:50:55      阅读:357      评论:0      收藏:0      [点我收藏+]

标签:

代码已经过测试

import re
import mmap
import os
import shutil

old_text=‘test‘
new_text=‘text‘
path=r‘C:\Users\Administrator\Desktop\2.txt‘
cpattern = re.compile(str(old_text))

with open(path,mode=‘rb‘) as r_file:
    try:
        # mmap throws a ValueError if the file is empty.
        r_data = mmap.mmap(r_file.fileno(),
                           0,
                           access=mmap.ACCESS_READ)
    except (ValueError, mmap.error):
        # size of file in /proc is 0, but contains data
        r_data = "".join(r_file)  
    result= re.sub(cpattern, new_text, r_data)
    r_data.close()
   
with open(path,mode=‘w‘) as w_file:
    w_file.write(result)

  

saltstack文件模块的replace操作简化

标签:

原文地址:http://www.cnblogs.com/slqt/p/5880794.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!