python批量替換資料夾內的檔案內容

2021-10-11 16:17:52 字數 1847 閱讀 1958

#author:jingyuan

import os

import re

#要改的資料夾

dir=

"e:\\testscript"

#要改的檔案型別(可以輸入多個)

file_type=

[".htm"

]#替換表(可以用python正規表示式)

look_up_table=[[

">map<"

,">list<"],

["a c"

,"a b"],

]def

get_filelist

(dir

,filetype)

: filelist =

for home, dirs, files in os.walk(

dir)

:for filename in files:

if(filename[

-len

(filetype):]

==filetype):)

return filelist

if __name__ ==

"__main__"

:for

type

in file_type:

print

("開始處理"

+type

+"型別檔案"

) file_list = get_filelist(

dir,

type

)print

("共發現"

+str

(len

(file_list))+

"個"+

type

+"型別檔案"

) replace_count=

0 file_count=

0for

file

in file_list:

file_count=file_count+1if

(file_count%

100==0)

:print

("修改到第"

+str

(file_count)

+"個檔案"

) file_data=

""with

open

(file

,"r"

, encoding=

"gb2312"

)as f:

for line in f:

for item in look_up_table:

if re.search(item[0]

, line)

:#print("正在修改從"+item[0]+"到"+item[1])

line=re.sub(item[0]

,item[1]

,line)

replace_count=replace_count+

1 file_data += line

with

open

(file

,"w"

,encoding=

"gb2312"

)as f:

f.write(file_data)

print

("一共進行了"

+str

(replace_count)

+"處替換"

)print

("結束處理"

+type

+"型別檔案"

)print

("全部結束"

)

批量替換資料夾名

bat檔案如下 echo off title 檔案bai名字元替du換 mode con cols 60 lines 20 檔案要是重名,會提示錯誤。setlocal enabledelayedexpansion color 0a 1set a set b set c cls echo.set p ...

python批量替換檔案內的字串

coding utf 8 import os import io def alter file,old str,new str 替換檔案中的字串 param file 檔名 param old str 就字串 param new str 新字串 return file data with io.op...

python 批量替換檔名

你要是這樣學習看到這種噁心不,需求來了,批量替換檔名 movie name os.listdir h 妙味課堂 獲取所有的檔名列表 去掉node ts koa vue 程式設計開發 2018最新node ts koa vue 全棧開發 前後端 完結 0,1項還有最後一項跟這個無關 moview na...