1. 程式人生 > 其它 >對資料夾中所有的txt文字操作,在指定行新增字串

對資料夾中所有的txt文字操作,在指定行新增字串


#add PASS ---------------
import os
filepath = os.path.abspath('.')
def eachFile(filepath):
pathDir = os.listdir(filepath) #獲取當前路徑下的檔名,返回List
for s in pathDir:
newDir=os.path.join(filepath,s) #將檔案命加入到當前檔案路徑後面
if os.path.isfile(newDir) : #如果是檔案
print("Running . . .")
if os.path.splitext(newDir)[1]==".txt": #判斷是否是txt
file = open(newDir, 'r')
content = file.read()
file.close()
pos = content.find("2.4G MAC address")
if pos != -1:
content = content[
:pos] + "\n" + "=========================================================================" + "\n" + "*****************" + "\n" + "**** P A S S ****" + "\n" + "*****************" + "\n" + content[
pos:]
file = open(newDir, "w")
file.write(content)
file.close()
pass
else:
eachFile(newDir) #如果不是檔案,遞迴這個資料夾的路徑

eachFile(filepath)