Python對文件修改,替換,刪除


一、修改原文件內容方式:

#!/usr/bin/env python
# -*- coding:utf8 -*-


old_str = "aaa" #老文件內容字段
new_str = "bbb" #要改成字段
file_data = ''
with open('/opt/1.txt', 'r', encoding='utf-8') as f:
    for line in f:
        if old_str in line:
            line = line.replace(old_str, new_str)
            file_data += line
with open('/opt/1.txt', 'w',encoding='utf-8') as f:
    f.write(file_data)

二、python 使用正則表達式 替換文件內容 re.sub 方法替換

import re,os
def alter(file,old_str,new_str):

    with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2:
        for line in f1:
            f2.write(re.sub(old_str,new_str,line))
    os.remove(file)
    os.rename("%s.bak" % file, file)
alter("file1", "admin", "password")

 

三、python 刪除文件一行

import shutil
with open('/path/to/file', 'r') as f:
    with open('/path/to/file.new', 'w') as g:
        for line in f.readlines():
            if '/local/server' not in line:             
                g.write(line)
shutil.move('/path/to/file.new', '/path/to/file')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM