Python文件操作中進(jìn)行字符串替換的方法(保存到新文件/當(dāng)前文件)
題目:
1.首先將文件:/etc/selinux/config 進(jìn)行備份 文件名為 /etc/selinux/config.bak
2.再文件:/etc/selinux/config 中的enforcing 替換為 disabled
# This file controls the state of SELinux on the system. # SELINUX= can take one of these three values: # enforcing - SELinux security policy is enforced. # permissive - SELinux prints warnings instead of enforcing. # disabled - No SELinux policy is loaded. SELINUX=disabled # SELINUXTYPE= can take one of three two values: # targeted - Targeted processes are protected, # minimum - Modification of targeted policy. Only selected processes are protected. # mls - Multi Level Security protection. SELINUXTYPE=enforcing
•方法一:用replace
import os import shutil def selinux_config(): """ 關(guān)閉SELINUX 修改文件內(nèi)容 :return: """ file_selinux = '/etc/selinux/config' backup_file_selinux = file_selinux + '.bak' temp_file_selinux = file_selinux + '.temp' if not os.path.exists(backup_file_selinux): shutil.copy2(file_selinux, backup_file_selinux) with open(file_selinux, mode='r') as fr, open(temp_file_selinux, mode='w') as fw: origin_line = 'SELINUX=enforcing' update_line = 'SELINUX=disabled' for line in fr: fw.write(line.replace(origin_line, update_line)) os.remove(file_selinux) os.rename(temp_file_selinux, file_selinux) if __name__ == '__main__': selinux_config()
•方法二:用re.sub
#! /usr/bin/env python # -*- coding: utf-8 -*- import os import re import shutil def selinux_config(): """ 關(guān)閉SELINUX 修改文件內(nèi)容 :return: """ file_selinux = '/etc/selinux/config' backup_file_selinux = file_selinux + '.bak' temp_file_selinux = file_selinux + '.temp' if not os.path.exists(backup_file_selinux): shutil.copy2(file_selinux, backup_file_selinux) with open(file_selinux, mode='r') as fr, open(temp_file_selinux, mode='w') as fw: origin_line = 'SELINUX=enforcing' update_line = 'SELINUX=disabled' for line in fr: re_sub_list = re.sub(origin_line, update_line, line) # 這里用re.sub進(jìn)行替換后放入 re_sub_list中 fw.writelines(re_sub_list) # 將列表中的每一行進(jìn)行寫入。writelines是將序列對象中的每一行進(jìn)行寫入。 os.remove(file_selinux) os.rename(temp_file_selinux, file_selinux) if __name__ == '__main__': selinux_config()
總結(jié)
以上所述是小編給大家介紹的Python文件操作中進(jìn)行字符串替換的方法(保存到新文件/當(dāng)前文件) ,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
python 解決selenium 中的 .clear()方法失效問題
這篇文章主要介紹了python 解決selenium 中的 .clear()方法失效問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09對python numpy數(shù)組中冒號的使用方法詳解
下面小編就為大家分享一篇對python numpy數(shù)組中冒號的使用方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04Python面向?qū)ο笕筇卣?封裝、繼承、多態(tài)
這篇文章主要介紹了Python面向?qū)ο笕筇卣?封裝、繼承、多態(tài),下面文章圍繞Python面向?qū)ο笕筇卣鞯南嚓P(guān)資料展開具體內(nèi)容,需要的朋友可以參考一下,希望對大家有所幫助2021-11-11