使用python替換文件內容


最新學習python使用到的替換文件文本的操作。

# 傳入文件(file),將舊內容(old_content)替換為新內容(new_content)
def replace(file, old_content, new_content):
    content = read_file(file)
    content = content.replace(old_content, new_content)
    rewrite_file(file, content)

# 讀文件內容
def read_file(file):
    with open(file, encoding='UTF-8') as f:
        read_all = f.read()
        f.close()

    return read_all

# 寫內容到文件
def rewrite_file(file, data):
    with open(file, 'w', encoding='UTF-8') as f:
        f.write(data)
        f.close()

# 替換操作(將test.txt文件中的'Hello World!'替換為'Hello Qt!')
replace(r'test.txt', 'Hello World!', 'Hello Qt!')


免責聲明!

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



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