对文件夹中所有的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)
posted @ 2021-11-08 13:21  江南王小帅  阅读(272)  评论(0)    收藏  举报