我正在尝试扫描目录和几个子目录下的所有文件中的字符串,替换它,当我执行替换时将其保存到新文件中, 我成功了 1)在文件夹和子文件夹中的所有文件中搜索字符串, 2)计算字符串的出现量 3)为拥有该字符串的人创建新文件。
但由于某种原因,我得到的新文件是空的,而不是包含替换字符串的旧文件的行。
这是我的代码:
import os
parentDirectory = "E:\ProjectPython\Test"
oldString = "oldString"
newString = "newString"
if (os.path.isdir(parentDirectory)):
for dirName,directories,files in os.walk(parentDirectory):
for fileName in files:
fullPath = os.path.join(dirName,fileName)
with open(fullPath) as file:
counter=0
for line in file:
if line.__contains__(oldString) or line.__contains__(oldString.lower()):
counter=counter+1
if counter>>0 :
with open(fullPath+".New","w") as newFile:
for line in file:
newFile.write(line.replace(oldString,newString))
print("File:"+fullPath+"\nStrings that were replaced:"+str(counter))
else:
print(parentDirectory+"is missing!")