首页 > 解决方案 > 如何通过文件夹中的多个文件搜索关键字&如果该单词存在用另一个单词替换该单词&输出文件名

问题描述

我想在文件夹中的多个文件中搜索特定关键字。如果找到关键字,我希望将这个词替换为另一个给定的词。如果发生该操作,则输出找到并替换该单词的文件名。我希望这可以在 python 中完成,但我不知道该怎么做。这些文件可以是txt 或任何可以用记事本打开和阅读的文件扩展名。

标签: python

解决方案


这是你要找的吗


# only searches in current directory files
# replace os.getcwd() by directory path of what you want to search or use a variable
import os

keyword = input("Enter Keyword to search : ")
replacement = input("Enter replacement string : ")

for filename in os.listdir(os.getcwd()):
   with open(os.path.join(os.getcwd(), filename), 'r') as f: # open in readonly mode
       content = f.read()
       if keyword in content:
           with open(os.path.join(os.getcwd(), filename), 'w') as fw: # open in write mode
               writecontent = content.replace(keyword, replacement)
               fw.write(writecontent)
               print(f"Keyword {keyword} found and replaced in file : {filename}")

推荐阅读