您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)Python文件操作中如何進(jìn)行字符串替換的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
題目:
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()
感謝各位的閱讀!關(guān)于“Python文件操作中如何進(jìn)行字符串替換”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。