使用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