python - 如何通过文件夹中的多个文件搜索关键字&如果该单词存在用另一个单词替换该单词&输出文件名
问题描述
我想在文件夹中的多个文件中搜索特定关键字。如果找到关键字,我希望将这个词替换为另一个给定的词。如果发生该操作,则输出找到并替换该单词的文件名。我希望这可以在 python 中完成,但我不知道该怎么做。这些文件可以是txt 或任何可以用记事本打开和阅读的文件扩展名。
解决方案
这是你要找的吗
# 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}")
推荐阅读
- shapes - Halcon - 获得分支分数
- bash - 尝试使用 awk 命令删除一些字符串
- java - 找不到基本名称的捆绑包警告
- javascript - Chrome 扩展:如何从活动选项卡中的控制台获取错误
- r - 如何估计函数中的参数?
- java - Java多维多类型数组(Map/List/Collection)?
- c++ - 如果匹配(从头开始),则删除字符串的第一部分的最简单方法?(使用升压是可以的)
- c++ - 我如何编写类似 std::variant 的开关之类的代码?
- r - R 4.0 使用 Rtools/ 而不是 rtools40/
- ansible - ansible-playbook 从文件中收集信息