使用python替換文件內容
- 2020 年 2 月 24 日
- 筆記
最新學習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!')