使用python替換檔案內容

2021-10-02 06:51:17 字數 912 閱讀 7916

最新學習python使用到的替換檔案文字的操作。

# 傳入檔案(file),將舊內容(old_content)替換為新內容(new_content)

defreplace

(file

, old_content, new_content)

: content = read_file(

file

) content = content.replace(old_content, new_content)

rewrite_file(

file

, content)

# 讀檔案內容

defread_file

(file):

with

open

(file

, encoding=

'utf-8'

)as f:

read_all = f.read(

) f.close(

)return read_all

# 寫內容到檔案

defrewrite_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!'

)

替換檔案內容

前幾天無意間看見一道題,內容大致是這樣的。有乙個檔案,裡面內容是這樣的格式 1 aa 2 bb 3 cc 4 dd 現在想插入3 ee,如果存在3 那麼把後面內容換成新內容,如果不存在則新增一行。一開始我是這麼寫的 後來經指點使用字典可以這麼寫 tmp with open 1 r as fd a f...

python 練習 替換檔案內容

1.替換 import re file name new 4.txt fp open file name,r alllines fp.readlines fp.close fp open file name,w for eachline in alllines a re.sub 0.0.0.0 1....

Python學習(8) 替換檔案內容

在前處理時替換檔案裡不被翻譯工具識別的內容。用 python 寫完指令碼後,實現 perl 指令碼呼叫 python 指令碼並執行。delete content 2.7.py coding utf 8 import os import re import io import sys str1 pri...